Skip to content
This repository was archived by the owner on Jan 16, 2019. It is now read-only.

Closurebinding

mikey179 edited this page Jul 30, 2012 · 4 revisions

Closure bindings

Available since release 2.1.0.

It might be useful to initialize some values lazy, but using an injection provider would be overblown. This is where closure bindings come in handy:

$binder->bind('Person')->toClosure(function() { return new Schst(); });
// other bindings

$injector = $binder->getInjector();
$bmw = $injector->getInstance('Car');

var_dump($schst);
var_dump($bmw);

The code inside the closure has to create the value, it doesn't have any access to the injector, so if there any dependencies they must be available at the moment the closure is created.

For class bindings the closure binding can be combined with scopes:

$binder->bind('Person')->toClosure(function() { return new Schst(); })->asSingleton();

Closure bindings are also available for constant bindings:

$binder->bindConstant('answer')->toClosure(function() { return 42; });
Clone this wiki locally