In CodeIgniter 4, Factories are utility tools that streamline the creation of class instances. They provide a simple and reusable way to generate objects dynamically without having to explicitly write repetitive new
instantiations or manual object creation logic. Factories are primarily used to manage instances of Models and Entities but can be extended for other classes.
Features of Factories:
- Dynamic Creation: Automatically locate and create instances of classes by their names.
- Reusability: Simplify repetitive object creation for Models, Entities, or other classes.
- Caching: Reduce overhead by caching objects, so multiple calls for the same class return the same instance.
- Convenience: Avoid hardcoding class names or locations in your code.
How Factories Work:
Factories are provided through CodeIgniter’s CodeIgniter\ModelFactory
and CodeIgniter\EntityFactory
utilities. The general approach is to ask the Factory for an instance, and it takes care of locating and creating the object dynamically.
Why Use Factories?
1. Simplified Object Creation:
- Avoid manually instantiating classes.
- Automatically locate and instantiate the required Model or Entity.
2. Performance Optimization:
- Use the built-in caching mechanism to avoid creating multiple instances of the same object unnecessarily.
3. Dynamic Behavior:
- Work with dynamic or unknown class names at runtime without worrying about manual instantiation logic.
Using Factories in CodeIgniter 4
1. Creating Model Instances
The model()
helper function acts as a Factory for Models.
Example:
$model = model('App\Models\UserModel');
// Use the model instance
$user = $model->find(1);
- Dynamic Model Resolution: The
model()
function will locate theUserModel
in theApp\Models
namespace by default. - Caching: By default,
model()
caches the instance, so subsequent calls for the same model return the same object.
Non-Shared Instance: If you want a fresh (non-cached) instance:
$model = model('App\Models\UserModel', false);
2. Creating Entity Instances
Entities represent single rows of data, and Factories help create them dynamically.
Example:
$entity = new \App\Entities\UserEntity();
Alternatively, you can integrate it with a Factory pattern for dynamic instantiation, although CodeIgniter 4 does not provide a dedicated helper like model()
for Entities. You would generally use new
or custom factories for this purpose.
3. Custom Class Instances
Factories can be extended to work with custom classes, not just Models or Entities. You would need to implement your custom factory logic for these.
Example:
namespace App\Factories;
class MyFactory
{
public static function create($className, ...$params)
{
if (!class_exists($className)) {
throw new \Exception("Class $className does not exist.");
}
return new $className(...$params);
}
}
// Usage
$myObject = \App\Factories\MyFactory::create(\App\Libraries\CustomClass::class);
Example of Factory for Reusability
Custom Factory Example:
namespace App\Factories;
class EntityFactory
{
protected static $cache = [];
public static function get(string $entityName)
{
if (!array_key_exists($entityName, static::$cache)) {
$class = "App\\Entities\\$entityName";
if (!class_exists($class)) {
throw new \InvalidArgumentException("Class $class does not exist.");
}
static::$cache[$entityName] = new $class();
}
return static::$cache[$entityName];
}
}
// Usage
$userEntity = \App\Factories\EntityFactory::get('UserEntity');
Built-In Helpers for Factories
1. model()
:
- Simplifies Model instantiation and management.
$userModel = model('App\Models\UserModel');
2. db()
(Database Factory):
- Retrieves the database connection service.
$db = db_connect();
3. service()
:
- Retrieves or creates a shared service instance.
$logger = service('logger');
When to Use Factories:
- When you need to create multiple instances of Models or Entities dynamically.
- When working with dynamic or unknown class names at runtime.
- To reduce boilerplate code and improve readability.
Benefits of Factories in CodeIgniter 4:
- Dynamic Flexibility: Easily create and reuse objects on the fly.
- Reduced Redundancy: Simplifies code by avoiding repetitive
new
statements. - Improved Performance: Caching ensures optimized resource usage.
- Clean Code: Centralized management of object creation logic.