drhino/container

Lightweight PSR-11 Container

v3.0.0 2023-04-10 17:46 UTC

This package is auto-updated.

Last update: 2024-12-10 21:21:59 UTC


README


Install with Composer:

composer require drhino/container:^3.0.0

Example use:

class Dependency
{
    public string $var = '';
}

class Init
{
    public function __construct(Dependency $dependency, String $value)
    {
        $dependency->var = $value;
    }
}
$container = new drhino\Container\Container;

$container
    ->add(Init::class, [
        // The arguments of the constructor
        'dependency' => $container->ref(Dependency::class),
        'value'      => 'Hello world',
    ])
    ->add(Dependency::class)
;

Use $container->ref() to reference an identifier before it has been added into the container.


// Executes __construct()
$init = $container->get(Init::class);

// Prints 'Hello world'
echo $container->get(Dependency::class)->var;

Signature:

The following are exactly the same:

$container->add(Dependency::class);
$container->add($id = Dependency::class, $resource = Dependency::class, $arguments = []);
$container->add($id = Dependency::class, $arguments = []);