Note:
If you use PHPStorm, you can copy the
resources/phpstorm.meta.php
file to your project root as.phpstorm.meta.php
for autocompletion onget()
andnew()
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.
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)
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)
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.
has(string $id) : bool
Returns true
if the Container can successfully get()
or new()
the $id
;
otherwise, false
.
$container->has(stdClass::CLASS); // true
$container->has('NoSuchClass'); // false
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)