Dependency Injection

Basic usage

Store a class instance with set()

You can store an class instance in the container with set().

$container->set(new ClimbingSession());

$class1 = $container->get(ClimbingSession::class);
$class2 = $container->get(ClimbingSession::class);

In example above, $class1 and $class2 will be the same instance of ClimbingSession.

Verify a stored class instance with has()

You can check if the container has particular stored class instance.

if ($container->has(Monolog\Logger::class)) {
    // ...
}

Delete a stored class instance with delete()

$container->delete(Logger::class);

Use aliases for class instance

// when setting (shorter)
$container->set(new Monolog\Handler\StreamHandler(), 'LogStream');
$stream = $container->get('LogStream');

// or with addAlias()
$container->addAlias(Monolog\Handler\StreamHandler::class, 'LogStream');
$container->set(new Monolog\Handler\StreamHandler);
$stream = $container->get('LogStream');

Resolve a class method dependencies with call()

You can also resolve dependencies of a object method withcall().

class Foo {
    public function method(Bar $bar, $arg) {
        // ...
        return 'ok';
    }
}

$foo = new Foo();
$response = $container->call([ $foo, 'method' ], 123);
echo $response; // output 'ok'