WpaeDi.php
61 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Wpae\Di; |
| 4 | |
| 5 | |
| 6 | class WpaeDi |
| 7 | { |
| 8 | private $config; |
| 9 | |
| 10 | private $cache; |
| 11 | |
| 12 | private $services; |
| 13 | |
| 14 | public function __construct($config) |
| 15 | { |
| 16 | |
| 17 | $this->config = $config; |
| 18 | |
| 19 | $this->services = [ |
| 20 | 'c' => [ |
| 21 | 'value' => 10 |
| 22 | ], |
| 23 | 'a' => [ |
| 24 | 'class' => '\Wpae\ClassA', |
| 25 | 'arguments' => [ |
| 26 | '@a', |
| 27 | '@b' |
| 28 | ] |
| 29 | ], |
| 30 | 'b' => [ |
| 31 | 'class' => '\Wpae\ClassB', |
| 32 | 'arguments' => [ |
| 33 | '@a', |
| 34 | '%c' |
| 35 | ] |
| 36 | ] |
| 37 | ]; |
| 38 | |
| 39 | } |
| 40 | |
| 41 | public function get($name) { |
| 42 | if(isset($this->cache[$name])) { |
| 43 | return $this->cache[$name]; |
| 44 | } |
| 45 | if(isset($this->services[$name])) { |
| 46 | $arguments = []; |
| 47 | if(count($this->services[$name]['arguments'])){ |
| 48 | foreach($this->services[$name]['arguments'] as $argument) { |
| 49 | $arguments[] = $this->get($argument); |
| 50 | } |
| 51 | } else { |
| 52 | $serviceClass = $this->services[$name]['class']; |
| 53 | $this->cache[$name] = new $serviceClass(); |
| 54 | return $this->cache[$name]; |
| 55 | } |
| 56 | $r = new \ReflectionClass($this->services[$name]['class']); |
| 57 | $this->cache[$name] = $r->newInstanceArgs($arguments); |
| 58 | } |
| 59 | return $this->cache[$name]; |
| 60 | } |
| 61 | } |