Service Container
Introductionβ
BowPHP's dependency injection container (DIC), called Capsule, is a powerful tool for managing your application's dependencies.
Dependency Injection (DI)β
Dependency injection lets you provide the objects a class needs instead of having it create them itself. This makes the code more modular and testable.
Inversion of Control (IoC)β
Inversion of control delegates the management of objects and their dependencies to a container. The container creates and manages the objects you need for you.
Accessing the containerβ
Via the app() helperβ
// Get the container instance
$container = app();
// Resolve a class directly
$service = app(App\Services\UserService::class);
Via the Capsule classβ
use Bow\Container\Capsule;
$container = Capsule::getInstance();
Registering bindingsβ
The container offers three primitives, distinguished by their lifecycle:
| Method | When is the object created? | Cached? |
|---|---|---|
bind($key, $value) | On the first resolution | Yes β reused afterwards |
instance($key, $obj) | Immediately (you pass it) | Yes β the provided instance is always returned |
factory($key, $value) | On every resolution | No β a new instance on each call |
Simple binding (bind)β
Registers a service that will be instantiated only once, then cached:
use Bow\Container\Capsule;
use App\Services\PaymentService;
app()->bind('payment', function (Capsule $container) {
return new PaymentService();
});
// Bind an interface to an implementation: Bow will use reflection to
// instantiate PaymentService and resolve its constructor dependencies.
app()->bind(PaymentServiceInterface::class, PaymentService::class);
Instance (singleton)β
Registers an already-created instance:
use App\Services\Config;
$config = new Config(['debug' => true]);
app()->instance('config', $config);
Factoryβ
Creates a new instance on each resolution:
use Bow\Container\Capsule;
app()->factory('uuid', function (Capsule $container) {
return new UuidGenerator();
});
// Each call creates a new instance
$uuid1 = app()->make('uuid');
$uuid2 = app()->make('uuid'); // Different instance
Resolving dependenciesβ
Simple resolutionβ
// Via make()
$service = app()->make('payment');
// Via the helper
$service = app('payment');
// Via a class
$service = app(App\Services\PaymentService::class);
Resolution with parametersβ
$service = app()->makeWith(App\Services\ReportService::class, [
'startDate' => '2024-01-01',
'endDate' => '2024-12-31'
]);
// Shortcut via the helper: if the 2nd argument is non-empty, app() automatically
// delegates to makeWith().
$service = app(App\Services\ReportService::class, [
'startDate' => '2024-01-01',
'endDate' => '2024-12-31',
]);
Array accessβ
The container implements ArrayAccess:
// Check existence
if (isset