Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- The Artax provider expects injection definitions to map constructor parameter names to the concrete classes that should be instantiated:
- ```php
- interface MyInterface {}
- class Implementation implements MyInterface {}
- class MyClass {
- public $dependency;
- public function __construct(MyInterface $dependency) {
- $this->dependency = $dependency;
- }
- }
- $provider = new Artax\Injection\Provider();
- // won't work because the provider doesn't know what to inject for
- // the non-concrete $dependency
- $provider->make('MyClass');
- // instead, define an injection definition:
- $provider->define('MyClass', array('dependency' => 'Implementation'));
- $obj = $provider->make('MyClass');
- var_dump($obj->dependency instanceof Implementation); // bool(true)
- ```
- *All* definitions are assumed to be class names **unless** the parameter name is preceded by `:` in the definition:
- ```php
- class SomeClass {
- public $arg1;
- public $arg2;
- public function __construct(SomeDependency $arg1, $arg2) {
- $this->arg1 = $arg1;
- $this->arg2 = $arg2;
- }
- }
- $provider->define('SomeClass', array('arg1'=>'SomeDependency', ':arg2'=>42));
- $obj = $provider->make('SomeClass');
- var_dump($obj->arg2); // int(42)
- ```
- The colon tells the Provider to treat the parameter value *NOT* as a class name but as its literal value.
- Here's an example of using scalar values to define an injection definition for all instantiations of the `PDO` class:
- ```php
- $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
- $user = 'dbuser';
- $pass = 'dbpass';
- $provider = new Artax\Injection\Provider();
- $provider->define('PDO', array(':dsn'=>$dsn, ':user'=>$user, ':pass'=>$pass));
- $provider->share('Pdo'); // handles class names case-insensitively (duh, PHP)
- $pdo = $provider->make('pDo'); // handles class names case-insensitively (duh, PHP)
- var_dump($pdo instanceof PDO); // bool(true)
- $pdo2 = $provider->make('PDO'); // returns same instance because PDO is "shared" above
- var_dump($pdo === $pdo2); // bool(true)
- ```
Add Comment
Please, Sign In to add comment