Guest User

Untitled

a guest
Nov 27th, 2018
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. The Artax provider expects injection definitions to map constructor parameter names to the concrete classes that should be instantiated:
  2.  
  3. ```php
  4. interface MyInterface {}
  5. class Implementation implements MyInterface {}
  6. class MyClass {
  7. public $dependency;
  8. public function __construct(MyInterface $dependency) {
  9. $this->dependency = $dependency;
  10. }
  11. }
  12.  
  13. $provider = new Artax\Injection\Provider();
  14.  
  15. // won't work because the provider doesn't know what to inject for
  16. // the non-concrete $dependency
  17. $provider->make('MyClass');
  18.  
  19. // instead, define an injection definition:
  20. $provider->define('MyClass', array('dependency' => 'Implementation'));
  21.  
  22. $obj = $provider->make('MyClass');
  23. var_dump($obj->dependency instanceof Implementation); // bool(true)
  24.  
  25. ```
  26.  
  27. *All* definitions are assumed to be class names **unless** the parameter name is preceded by `:` in the definition:
  28.  
  29. ```php
  30. class SomeClass {
  31. public $arg1;
  32. public $arg2;
  33. public function __construct(SomeDependency $arg1, $arg2) {
  34. $this->arg1 = $arg1;
  35. $this->arg2 = $arg2;
  36. }
  37. }
  38. $provider->define('SomeClass', array('arg1'=>'SomeDependency', ':arg2'=>42));
  39. $obj = $provider->make('SomeClass');
  40. var_dump($obj->arg2); // int(42)
  41.  
  42. ```
  43.  
  44. The colon tells the Provider to treat the parameter value *NOT* as a class name but as its literal value.
  45.  
  46. Here's an example of using scalar values to define an injection definition for all instantiations of the `PDO` class:
  47.  
  48. ```php
  49. $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
  50. $user = 'dbuser';
  51. $pass = 'dbpass';
  52.  
  53. $provider = new Artax\Injection\Provider();
  54. $provider->define('PDO', array(':dsn'=>$dsn, ':user'=>$user, ':pass'=>$pass));
  55. $provider->share('Pdo'); // handles class names case-insensitively (duh, PHP)
  56. $pdo = $provider->make('pDo'); // handles class names case-insensitively (duh, PHP)
  57.  
  58. var_dump($pdo instanceof PDO); // bool(true)
  59.  
  60. $pdo2 = $provider->make('PDO'); // returns same instance because PDO is "shared" above
  61. var_dump($pdo === $pdo2); // bool(true)
  62. ```
Add Comment
Please, Sign In to add comment