-
Notifications
You must be signed in to change notification settings - Fork 0
Docs IOC InjectInstances
In some cases you might need to inject a dependency, that is not managed by the IoC framework of Stubbles, but created by your own code. The last two features help you solve this problem.
Instead of binding a type to a concrete implementation, you can always bind it to an existing instance. In the following example, you already have an instance of the class Schst created and you want to inject this into the BMW instance, instead of letting the IoC framework create a new instance:
#php <?php $schst = new Schst(); $binder->bind('Person')->toInstance($schst); // other bindings $injector = $binder->getInjector(); $bmw = $injector->getInstance('Car'); var_dump($schst); var_dump($bmw); ?>
Instead of using the to() method to specify the binding, you only need to call toInstance() and pass the object to use for the binding. The result of this script is:
object(Schst)#14 (0) { } object(BMW)#38 (4) { ["driver:protected"]=> object(Schst)#14 (0) { } ["coDriver:protected"]=> object(Mikey)#55 (0) { } ["engine:protected"]=> object(TwoLitresEngine)#42 (0) { } ["tire:protected"]=> object(Goodyear)#45 (0) { } }
As you can see, the BMW instance contains a reference to the Schst instance you created, there object handle is !#14. Please note that this type of binding acts similarly as binding a class into the singleton scope as described above.