kanian / containerx
A simple PHP DI container
This package is auto-updated.
Last update: 2024-10-21 21:27:30 UTC
README
ContainerX is a little PHP dependency injection container.
Installation
$ composer require kanian/containerx
Usage
Let:
The Car class be:
class Car { protected $driver; public function __construct(Driver $driver) { $this -> driver = $driver; } \\\ ... more car code }
And the HumanDriver class be:
class HumanDriver implements Driver { public function drive() { \\\ ... some driving code } }
We can use:
Container functionalities as object methods
In order to access the functionalities of the container as object methods:
use Kanian\ContainerX\Container; $container = new Container(); $container->set('chauffeur', function($c){ return new HumanDriver;}); $container->set('limo', function($c){ return new Car($c->get('chauffeur'));}); $limo = $container->get('limo');
We have used anonymous functions has factories. Moreover, We could simply register the dependencies we need and let the container instantiate them:
use Kanian\ContainerX\Container; $container = new Container(); $container->set('chauffeur',HumanDriver::class); $container->set('limo',Car::class); $limo = $container->get('limo');
The container will know how to construct a Car instance for us.
Alternatively, we can use:
Container functionalities through the ArrayAccess Interface
For example, we can achieve factory based registration by using the Kanian\Container\ContainerX class, which implements the ArrayAccess interface.
use Kanian\ContainerX\ContainerX; $container = new ContainerX(); $container['chauffeur'] = HumanDriver::class; $container['limo'] = Car::class; $limo = $container['limo'];
Accessing a dependency as a Singleton
In order to ensure that there is receive only one copy of a dependency in the system at a time, you will use the
singletonize
method. like this:
$container->singletonize('limo', Car::class); $limo = $container['limo'];
Now you will always get the same instance of Car, but with different instances of HumanDriver..