-
Notifications
You must be signed in to change notification settings - Fork 0
Docs IOC ConstantValues
Until now, you used the Stubbles IoC framework only to inject objects. However, it is also possible to inject constant values into objects. The following example shows, how this can be done. Imagine, you have a class, that requires the connection parameters for a database:
#php <?php class MyApplication { protected $dbParams; /** ***@Inject ***@Named('dbParams') ***/ public function setDbParams($params) { $this->dbParams = $params; } // other methods of the class } ?>
As in the examples before, you annotated the method that should be used to inject the database connection parameters with the @Inject and the @Named annotation. When injecting non-objects, the @Named annotation is required, as there is no type hint to identify the binding.
Now, all that's left to do is specify a binding for the constant dbParams:
#php <?php // make sure, the IoC functionality is loaded stubClassLoader::load('net::stubbles::ioc::stubBinder'); $binder = new stubBinder(); $binder->bindConstant()->named('dbParams')->to('mysql:host=localhost;dbname=test'); $injector = $binder->getInjector(); $app = $injector->getInstance('MyApplication'); ?>
The $injector will now return a configured instance of MyApplication with the $dbParams property set.
The Stubbles IoC framework is not meant to replace your own configuration framework, but in some cases, injecting constant values can be helpful or might even be a requirement for your application to work:
Injecting constants works everywhere where @Named annotation can be applied.
Starting with release 1.1.0 there is also the possibility to retrieve constant values directly from the binder:
$dbParams = $injector->getConstant('dbParams');
Before 1.1.0 you have to use a workaround:
$dbParams = $injector->getInstance(stubConstantBinding::TYPE, 'dbParams');