Using and Creating Libraries
Relevant source files
The following files were used as context for generating this wiki page:
In CodeIgniter 4, "Libraries" are classes that provide a specific set of functionalities, designed to be reusable throughout your application. While you can create and use simple classes, the framework strongly encourages managing them as Services. Services provide a centralized and consistent way to access library instances, ensuring that only one instance of a service is active at any time, which is both efficient and convenient.
This guide covers the creation of custom libraries, the process of registering them as services, and the various methods for accessing them within your application, such as in controllers or other classes. Understanding these concepts is fundamental to building a modular and maintainable CodeIgniter 4 application.
Sources: source/general/creating_libraries.rst:3-10, source/concepts/services.rst:3-8
Creating a Library
Creating a library is as simple as creating a new class. The class can contain any logic you need to encapsulate. For CodeIgniter's autoloader to find your library without any additional configuration, you should place the file within the app/Libraries directory. The class name must match the filename and be capitalized.
Sources: source/general/creating_libraries.rst:15-20, source/concepts/autoloader.rst:37-41
Basic Library Structure
A library is a standard PHP class. It should have a namespace corresponding to its location in the directory structure. For a library located at app/Libraries/Someclass.php, the namespace would be App\Libraries.
<?php
namespace App\Libraries;
class Someclass
{
public function someMethod()
{
// ...
}
}
Sources: source/general/creating_libraries.rst:22-33
The following diagram illustrates the standard location for a custom library file.
Using a Library
Once a library class is created, you can use it in your controllers or other classes. There are two primary methods for this: direct instantiation and using the Services facility.
Sources: source/general/creating_libraries.rst:35-37
Direct Instantiation
You can create a new instance of your library class directly, just like any other PHP class.
<?php
namespace App\Controllers;
use App\Libraries\Someclass;
class MyController extends BaseController
{
public function index()
{
$someclass = new Someclass();
$someclass->someMethod();
}
}
Sources: source/general/creating_libraries.rst:39-53
Using CodeIgniter Services
The recommended method for managing and accessing libraries is through CodeIgniter's Services. A service is a factory function that creates and returns a new or shared instance of a class. This approach offers several advantages:
- Performance: It ensures only one instance of a class is created, which is then shared across the application.
- Ease of Use: Accessing services is simple and consistent.
- Testability: Services can be easily replaced with mock objects during testing.
Sources: source/concepts/services.rst:3-13
Configuring a Library as a Service
To make your library available as a service, you must register it in the app/Config/Services.php file. You add a new static method that is responsible for creating and returning an instance of your library. The method should check if a shared instance already exists before creating a new one.
// In app/Config/Services.php
use Config\BaseService;
use App\Libraries\Someclass;
class Services extends BaseService
{
public static function someclass($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('someclass');
}
return new Someclass();
}
}
Sources: source/general/creating_libraries.rst:55-79, source/concepts/services.rst:20-33
The table below outlines the key parameters and patterns for service definition.
| Component | Description | Example |
|---|---|---|
public static function | The method that acts as the factory for the service. The name is how you will call the service (e.g., someclass). | public static function someclass(...) |
$getShared | A boolean parameter to control whether a new instance or a shared instance is returned. Defaults to true. | if ($getShared) { ... } |
static::getSharedInstance() | A helper method from BaseService that returns the existing shared instance or creates, stores, and returns a new one. | return static::getSharedInstance('someclass'); |
Sources: source/concepts/services.rst:20-43
Accessing the Service
Once configured, you can access your library from anywhere in your application using two main methods.
- The
service()function: This is a global helper function that provides a convenient way to get a service instance. - The
Servicesclass: You can call the static factory method directly on theConfig\Servicesclass.
The service() function is generally preferred for its brevity.
// Using the service() function
$someclass = service('someclass');
// Using the Services class directly
$someclass = \Config\Services::someclass();
Sources: source/general/creating_libraries.rst:81-89, source/general/common_functions.rst:111-114
The following sequence diagram shows the flow of retrieving a shared service instance using the service() helper.
Core Libraries as Services
Many of CodeIgniter's core features are provided as services, which serves as a practical example of this pattern. The Session library, for instance, is accessed via service('session'). Its configuration is handled in app/Config/Services.php where the framework's default service file is extended.
// Accessing the core Session library
$session = service('session');
$session->set('my_item', 'my_value');
Sources: source/libraries/sessions.rst:104-106, source/libraries/sessions.rst:12-14
This demonstrates that the service pattern is used consistently for both custom-built libraries and framework-native components, promoting a unified architecture.
Summary
CodeIgniter 4 provides a flexible system for creating and using libraries. While direct instantiation is possible, the framework's service-oriented architecture is the recommended approach. By defining libraries as services in app/Config/Services.php, you gain the benefits of a shared, single-instance pattern that is performant, easy to manage, and simple to use via the service() helper function. This approach is central to building robust and maintainable applications with CodeIgniter 4.
Sources: source/general/creating_libraries.rst, source/concepts/services.rst