1.2. Container Usage

Note:

If you use PHPStorm, you can copy the resources/phpstorm.meta.php file to your project root as .phpstorm.meta.php for autocompletion on get() and new() method calls.

After instantiating a Container ...

use Capsule\Di\Container;
use Capsule\Di\Definitions;

$def = new Definitions();
$container = new Container($def);

... use its methods to retrieve identified objects and values.

1.2.1. Retrieving Shared Instances

get(string $id) : mixed

Returns a shared instance of the defined class. Multiple calls to get() return the same object.

$foo1 = $container->get(Foo::CLASS);
$foo2 = $container->get(Foo::CLASS);
var_dump($foo1 === $foo2); // bool(true)

1.2.2. Retrieving New Instances

new(string $id) : mixed

Returns a new instance of the defined class. Multiple calls to new() return different new object instances.

$foo1 = $container->new(Foo::CLASS);
$foo2 = $container->new(Foo::CLASS);
var_dump($foo1 === $foo2); // bool(false)

1.2.3. Retrieving Values

You can use get() to retrieve defined primitive values.

$host = $container->get('db.host');

If a primitive value defined as a Lazy, multiple calls to get() will return the same value. However, multiple calls to new() may return different values, as the Lazy will be re-evaluated on each call.

1.2.4. Checking For Existence

has(string $id) : bool

Returns true if the Container has that identifier in its Definitions, or if the identifier is is an existing class; otherwise, false.

$container->has(stdClass::CLASS); // true
$container->has('NoSuchClass'); // false

1.2.5. Callable Factories

callableGet(string $id) : callable

callableNew(string $id) : callable

These return a call to get() or new() wrapped in a closure. Useful for providing factories to other containers.

$callableGet = $container->callableGet(Foo::CLASS);
$foo1 = $callableGet();
$foo2 = $callableGet();
var_dump($foo1 === $foo2); // bool(true)

$callableNew = $container->callableNew(Foo::CLASS);
$foo1 = $callableNew();
$foo2 = $callableNew();
var_dump($foo1 === $foo2); // bool(false)