1. 程式人生 > >【設計思想】依賴註入

【設計思想】依賴註入

構造函數 magic clas 實例 reg 調整 emca sde sta

場景:傳統的思路是應用程序用到一個Foo類,就會創建Foo類並調用Foo類的方法,假如這個方法內需要一個Bar類,就會創建Bar類並調用Bar類的方法,而這個方法內需要一個Bim類,就會創建Bim類,接著做些其它工作。

【代碼1】

技術分享
 1 class Bim
 2     {
 3         public function doSomething()
 4         {
 5             echo __METHOD__, ‘|‘;
 6         }
 7     }
 8     
 9     class Bar
10     {
11         public
function doSomething() 12 { 13 $bim = new Bim(); 14 $bim->doSomething(); 15 echo __METHOD__, ‘|‘; 16 } 17 } 18 19 class Foo 20 { 21 public function doSomething() 22 { 23 $bar = new Bar(); 24 $bar
->doSomething(); 25 echo __METHOD__; 26 } 27 } 28 29 $foo = new Foo(); 30 $foo->doSomething(); //Bim::doSomething|Bar::doSomething|Foo::doSomething
View Code

使用依賴註入的思路是應用程序用到Foo類,Foo類需要Bar類,Bar類需要Bim類,那麽先創建Bim類,再創建Bar類並把Bim註入,再創建Foo類,並把Bar類註入,再調用Foo方法,Foo調用Bar方法,接著做些其它工作。

技術分享
 1 class Bim
 2     {
 3         public function doSomething()
 4         {
 5             echo __METHOD__, ‘|‘;
 6         }
 7     }
 8     
 9     class Bar
10     {
11         private $bim;
12     
13         public function __construct(Bim $bim)
14         {
15             $this->bim = $bim;
16         }
17     
18         public function doSomething()
19         {
20             $this->bim->doSomething();
21             echo __METHOD__, ‘|‘;
22         }
23     }
24     
25     class Foo
26     {
27         private $bar;
28     
29         public function __construct(Bar $bar)
30         {
31             $this->bar = $bar;
32         }
33     
34         public function doSomething()
35         {
36             $this->bar->doSomething();
37             echo __METHOD__;
38         }
39     }
40     
41     $foo = new Foo(new Bar(new Bim()));
42     $foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething
View Code

這就是控制反轉模式。依賴關系的控制反轉到調用鏈的起點。這樣你可以完全控制依賴關系,通過調整不同的註入對象,來控制程序的行為。例如Foo類用到了memcache,可以在不修改Foo類代碼的情況下,改用redis。

使用依賴註入容器後的思路是應用程序需要到Foo類,就從容器內取得Foo類,容器創建Bim類,再創建Bar類並把Bim註入,再創建Foo類,並把Bar註入,應用程序調用Foo方法,Foo調用Bar方法,接著做些其它工作.

總之容器負責實例化,註入依賴,處理依賴關系等工作

代碼演示 依賴註入容器 (dependency injection container)

通過一個最簡單的容器類來解釋一下

技術分享
 1 class Container
 2     {
 3         private $s = array();
 4     
 5         function __set($k, $c)
 6         {
 7             $this->s[$k] = $c;
 8         }
 9     
10         function __get($k)
11         {
12             return $this->s[$k]($this);
13         }
14     }
View Code

這段代碼使用了魔術方法,在給不可訪問屬性賦值時,__set() 會被調用。讀取不可訪問屬性的值時,__get() 會被調用。

技術分享
 1 $c = new Container();
 2     
 3     $c->bim = function () {
 4         return new Bim();
 5     };
 6     $c->bar = function ($c) {
 7         return new Bar($c->bim);
 8     };
 9     $c->foo = function ($c) {
10         return new Foo($c->bar);
11     };
12     
13     // 從容器中取得Foo
14     $foo = $c->foo;
15     $foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething
View Code

這段代碼使用了匿名函數

再來一段簡單的代碼演示一下,容器代碼來自simple di container

技術分享
 1 class IoC
 2     {
 3         protected static $registry = [];
 4     
 5         public static function bind($name, Callable $resolver)
 6         {
 7             static::$registry[$name] = $resolver;
 8         }
 9     
10         public static function make($name)
11         {
12             if (isset(static::$registry[$name])) {
13                 $resolver = static::$registry[$name];
14                 return $resolver();
15             }
16             throw new Exception(‘Alias does not exist in the IoC registry.‘);
17         }
18     }
19     
20     IoC::bind(‘bim‘, function () {
21         return new Bim();
22     });
23     IoC::bind(‘bar‘, function () {
24         return new Bar(IoC::make(‘bim‘));
25     });
26     IoC::bind(‘foo‘, function () {
27         return new Foo(IoC::make(‘bar‘));
28     });
29     
30     
31     // 從容器中取得Foo
32     $foo = IoC::make(‘foo‘);
33     $foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething
View Code

這段代碼使用了後期靜態綁定

依賴註入容器 (dependency injection container) 高級功能

技術分享
  1 class Bim
  2     {
  3         public function doSomething()
  4         {
  5             echo __METHOD__, ‘|‘;
  6         }
  7     }
  8     
  9     class Bar
 10     {
 11         private $bim;
 12     
 13         public function __construct(Bim $bim)
 14         {
 15             $this->bim = $bim;
 16         }
 17     
 18         public function doSomething()
 19         {
 20             $this->bim->doSomething();
 21             echo __METHOD__, ‘|‘;
 22         }
 23     }
 24     
 25     class Foo
 26     {
 27         private $bar;
 28     
 29         public function __construct(Bar $bar)
 30         {
 31             $this->bar = $bar;
 32         }
 33     
 34         public function doSomething()
 35         {
 36             $this->bar->doSomething();
 37             echo __METHOD__;
 38         }
 39     }
 40     
 41     class Container
 42     {
 43         private $s = array();
 44     
 45         public function __set($k, $c)
 46         {
 47             $this->s[$k] = $c;
 48         }
 49     
 50         public function __get($k)
 51         {
 52             // return $this->s[$k]($this);
 53             return $this->build($this->s[$k]);
 54         }
 55     
 56         /**
 57          * 自動綁定(Autowiring)自動解析(Automatic Resolution)
 58          *
 59          * @param string $className
 60          * @return object
 61          * @throws Exception
 62          */
 63         public function build($className)
 64         {
 65             // 如果是匿名函數(Anonymous functions),也叫閉包函數(closures)
 66             if ($className instanceof Closure) {
 67                 // 執行閉包函數,並將結果
 68                 return $className($this);
 69             }
 70     
 71             /** @var ReflectionClass $reflector */
 72             $reflector = new ReflectionClass($className);
 73     
 74             // 檢查類是否可實例化, 排除抽象類abstract和對象接口interface
 75             if (!$reflector->isInstantiable()) {
 76                 throw new Exception("Can‘t instantiate this.");
 77             }
 78     
 79             /** @var ReflectionMethod $constructor 獲取類的構造函數 */
 80             $constructor = $reflector->getConstructor();
 81     
 82             // 若無構造函數,直接實例化並返回
 83             if (is_null($constructor)) {
 84                 return new $className;
 85             }
 86     
 87             // 取構造函數參數,通過 ReflectionParameter 數組返回參數列表
 88             $parameters = $constructor->getParameters();
 89     
 90             // 遞歸解析構造函數的參數
 91             $dependencies = $this->getDependencies($parameters);
 92     
 93             // 創建一個類的新實例,給出的參數將傳遞到類的構造函數。
 94             return $reflector->newInstanceArgs($dependencies);
 95         }
 96     
 97         /**
 98          * @param array $parameters
 99          * @return array
100          * @throws Exception
101          */
102         public function getDependencies($parameters)
103         {
104             $dependencies = [];
105     
106             /** @var ReflectionParameter $parameter */
107             foreach ($parameters as $parameter) {
108                 /** @var ReflectionClass $dependency */
109                 $dependency = $parameter->getClass();
110     
111                 if (is_null($dependency)) {
112                     // 是變量,有默認值則設置默認值
113                     $dependencies[] = $this->resolveNonClass($parameter);
114                 } else {
115                     // 是一個類,遞歸解析
116                     $dependencies[] = $this->build($dependency->name);
117                 }
118             }
119     
120             return $dependencies;
121         }
122     
123         /**
124          * @param ReflectionParameter $parameter
125          * @return mixed
126          * @throws Exception
127          */
128         public function resolveNonClass($parameter)
129         {
130             // 有默認值則返回默認值
131             if ($parameter->isDefaultValueAvailable()) {
132                 return $parameter->getDefaultValue();
133             }
134     
135             throw new Exception(‘I have no idea what to do here.‘);
136         }
137     }
138     
139     // ----
140     $c = new Container();
141     $c->bar = ‘Bar‘;
142     $c->foo = function ($c) {
143         return new Foo($c->bar);
144     };
145     // 從容器中取得Foo
146     $foo = $c->foo;
147     $foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething
148     
149     // ----
150     $di = new Container();
151     
152     $di->foo = ‘Foo‘;
153     
154     /** @var Foo $foo */
155     $foo = $di->foo;
156     
157     var_dump($foo);
158     /*
159     Foo#10 (1) {
160       private $bar =>
161       class Bar#14 (1) {
162         private $bim =>
163         class Bim#16 (0) {
164         }
165       }
166     }
167     */
168     
169     $foo->doSomething(); // Bim::doSomething|Bar::doSomething|Foo::doSomething
View Code

以上代碼的原理參考PHP官方文檔:反射,PHP 5 具有完整的反射 API,添加了對類、接口、函數、方法和擴展進行反向工程的能力。 此外,反射 API 提供了方法來取出函數、類和方法中的文檔註釋。

若想進一步提供一個數組訪問接口,如$di->foo可以寫成$di‘foo‘],則需用到[ArrayAccess(數組式訪問)接口 。

一些復雜的容器會有許多特性

【設計思想】依賴註入