Skip to main content
Version: 5.x

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:

MethodWhen is the object created?Cached?
bind($key, $value)On the first resolutionYes β€” reused afterwards
instance($key, $obj)Immediately (you pass it)Yes β€” the provided instance is always returned
factory($key, $value)On every resolutionNo β€” 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