PHP如何實(shí)現(xiàn)依賴注入
摘要: 控制反轉(zhuǎn)(Inversion of Control,英文縮寫為IoC)是框架的重要特征??刂品崔D(zhuǎn)(IOC)是一種思想,依賴注入(DI)是實(shí)施這種思想的方法。
高層模塊不應(yīng)該依賴于底層模塊,兩個(gè)都應(yīng)該依賴抽象。
抽象不應(yīng)該依賴于細(xì)節(jié),細(xì)節(jié)應(yīng)該依賴于抽象。
首先,我們來看一段代碼:
- class A{
- public function echo()
- {
- echo 'A'.PHP_EOL;
- }
- }
- class EchoT {
- protected $t;
- public function __construct()
- {
- $this->t = new A();
- }
- public function echo(){
- $this->t->echo();
- }
- }
初始,我們都使用new 的方式在內(nèi)部進(jìn)行,EchoT類嚴(yán)重依賴于類A。每當(dāng)類A變化時(shí),EchoT類也得進(jìn)行變化。
我們優(yōu)化一下代碼
- class EchoT {
- protected $t;
- public function __construct($t) //構(gòu)造器注入由構(gòu)造器注入到其中
- {
- $this->t = $t;
- }
可以看到,這樣做的話。很大程序上,我們對(duì)程序進(jìn)行了解耦。類A無論你如何變動(dòng),EchoT類是不需要變動(dòng)的。不再依賴于A。但是新問題又來了,我們現(xiàn)在只有A,萬一來了B,來了CDEFG怎么辦。
面向接口
- interface T{
- public function echo();
- }
- class A{
- public function echo()
- {
- echo 'A'.PHP_EOL;
- }
- }
- class B implements T{
- public function echo()
- {
- echo 'B'.PHP_EOL;
- }
- }
- class EchoT {
- protected $t;
- public function __construct(T $t) //構(gòu)造器注入由構(gòu)造器注入到其中
- {
- $this->t = $t;
- }
- public function echo(){
- $this->t->echo();
- }
- }
將T抽象出為接口,這樣,EchoT類中的echo方法變成一個(gè)抽象的方法,不到運(yùn)行那一刻,不知道他們的Method方式是怎么實(shí)現(xiàn)的。
工廠
- function getT($str) {
- if(class_exists($str)){
- return new $str();
- }
- }
T要使用哪個(gè)是不明確的,因此,我們可以將其工廠化。【看上去很簡(jiǎn)單,在DI實(shí)際上有體現(xiàn)】
DI(重點(diǎn)來了)
首先,我們看一下PHP的psr規(guī)范。
http://www.php-fig.org/psr/psr-11/
官方定義的接口
Psr\Container\ContainerInterface
包含兩個(gè)方法
function get($id);
function has($id);
仔細(xì)看上面的工廠,是不是和get($id)很一致,PHP官方將其定義為容器(Container,我個(gè)人理解,就是一個(gè)復(fù)雜的工廠)
dependency injection container
依賴注入容器
- namespace Core;
- use Psr\Container\ContainerInterface;
- class Container implements ContainerInterface
- {
- protected $instance = [];//對(duì)象存儲(chǔ)的數(shù)組
- public function __construct($path) {
- $this->_autoload($path); //首先我們要自動(dòng)加載 psr-autoload
- }
- public function build($className)
- {
- if(is_string($className) and $this->has($className)) {
- return $this->get($className);
- }
- //反射
- $reflector = new \ReflectionClass($className);
- if (!$reflector->isInstantiable()) {
- throw new \Exception("Can't instantiate ".$className);
- }
- // 檢查類是否可實(shí)例化, 排除抽象類abstract和對(duì)象接口interface
- if (!$reflector->isInstantiable()) {
- throw new \Exception("Can't instantiate ".$className);
- }
- /** @var \ReflectionMethod $constructor 獲取類的構(gòu)造函數(shù) */
- $constructor = $reflector->getConstructor();
- // 若無構(gòu)造函數(shù),直接實(shí)例化并返回
- if (is_null($constructor)) {
- return new $className;
- }
- // 取構(gòu)造函數(shù)參數(shù),通過 ReflectionParameter 數(shù)組返回參數(shù)列表
- $parameters = $constructor->getParameters();
- // 遞歸解析構(gòu)造函數(shù)的參數(shù)
- $dependencies = $this->getDependencies($parameters);
- // 創(chuàng)建一個(gè)類的新實(shí)例,給出的參數(shù)將傳遞到類的構(gòu)造函數(shù)。
- $class = $reflector->newInstanceArgs($dependencies);
- $this->instance[$className] = $class;
- return $class;
- }
- /**
- * @param array $parameters
- * @return array
- */
- public function getDependencies(array $parameters)
- {
- $dependencies = [];
- /** @var \ReflectionParameter $parameter */
- foreach ($parameters as $parameter) {
- /** @var \ReflectionClass $dependency */
- $dependency = $parameter->getClass();
- if (is_null($dependency)) {
- // 是變量,有默認(rèn)值則設(shè)置默認(rèn)值
- $dependencies[] = $this->resolveNonClass($parameter);
- } else {
- // 是一個(gè)類,遞歸解析
- $dependencies[] = $this->build($dependency->name);
- }
- }
- return $dependencies;
- }
- /**
- * @param \ReflectionParameter $parameter
- * @return mixed
- * @throws \Exception
- */
- public function resolveNonClass(\ReflectionParameter $parameter)
- {
- // 有默認(rèn)值則返回默認(rèn)值
- if ($parameter->isDefaultValueAvailable()) {
- return $parameter->getDefaultValue();
- }
- throw new \Exception($parameter->getName().' must be not null');
- }
- /**
- * 參照psr-autoload規(guī)范
- * @param $path
- */
- public function _autoload($path) {
- spl_autoload_register(function(string $class) use ($path) {
- $file = DIRECTORY_SEPARATOR.str_replace('\\',DIRECTORY_SEPARATOR, $class).'.php';
- if(is_file($path.$file)) {
- include($path.$file);
- return true;
- }
- return false;
- });
- }
- public function get($id)
- {
- if($this->has($id)) {
- return $this->instance[$id];
- }
- if(class_exists($id)){
- return $this->build($id);
- }
- throw new ClassNotFoundException('class not found'); //實(shí)現(xiàn)的PSR規(guī)范的異常
- }
- public function has($id)
- {
- return isset($this->instance[$id]) ? true : false;
- }
- }
使用示例
- $container = new Container('../');//假設(shè)這是路徑
- $echoT = $container->get(\Test\EchoT::class); //假設(shè)echoT類的命名空間是\Test
- $echoT->echo();
這個(gè)時(shí)候,會(huì)出現(xiàn)一個(gè)問題:
- // 檢查類是否可實(shí)例化, 排除抽象類abstract和對(duì)象接口interface
- if (!$reflector->isInstantiable()) {
- throw new \Exception("Can't instantiate ".$className);
因?yàn)榻涌赥是無法實(shí)例化的,所以,一般在程序內(nèi),我們都加上別名(參照l(shuí)aravel框架)
- $container->alisa(\Test\T::class,\Test\T\A::class); //指定接口T使用類A(控制反轉(zhuǎn))
針對(duì)接口
下面是alias方法
- public function alias(string $key, $class, bool $singleton = true)
- {
- if($singleton) {
- $this->singleton[] = $class;
- }
- $this->aliases[$key] = $class;
- return $this;
- }
- //同時(shí),我們需要在build的時(shí)候進(jìn)行判斷是否為別名
- public function build($className)
- {
- if(is_string($className) and $this->has($className)) {
- return $this->get($className);
- }
- if(isset($this->aliases[$className])) {
- if(is_object($this->aliases[$className])) {
- return $this->aliases[$className];
- }
- $className = $this->aliases[$className];
- }
就此,一個(gè)簡(jiǎn)單的PHP容器就實(shí)現(xiàn)了。