Core

Bindings

How `set()` and `singleton()` work, with explicit class and factory bindings.

set vs singleton

set() is transient (new resolve each call). singleton() is shared and cached in container instances map.

example.php
$container->set(FooFormatter::class, FooFormatter::class);
$container->singleton(BarCache::class, BarCache::class);

Factory binding

Use closure binding when constructor needs config values or runtime composition.

example.php
$container->singleton(HttpClientInterface::class, static function (ContainerInterface $container): HttpClientInterface {
    $config = $container->get(HttpClientConfig::class);

    return new Client([
        'timeout' => $config->timeout,
    ]);
});