溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在PHP中實(shí)現(xiàn)依賴注入

發(fā)布時(shí)間:2021-06-30 15:42:23 來源:億速云 閱讀:137 作者:Leah 欄目:編程語言

這篇文章給大家介紹如何在PHP中實(shí)現(xiàn)依賴注入,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

首先,我們來看一段代碼:

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;         }

可以看到,這樣做的話。很大程序上,我們對程序進(jìn)行了解耦。類A無論你如何變動,EchoT類是不需要變動的。不再依賴于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è)是不明確的,因此,我們可以將其工廠化?!究瓷先ズ芎唵?,在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 = [];//對象存儲的數(shù)組         public function __construct($path) {                 $this->_autoload($path);  //首先我們要自動加載  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和對象接口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í)候,會出現(xiàn)一個(gè)問題:

// 檢查類是否可實(shí)例化, 排除抽象類abstract和對象接口interface                 if (!$reflector->isInstantiable()) {                         throw new \Exception("Can't instantiate ".$className);

因?yàn)榻涌赥是無法實(shí)例化的,所以,一般在程序內(nèi),我們都加上別名(參照laravel框架)

$container->alisa(\Test\T::class,\Test\T\A::class); //指定接口T使用類A(控制反轉(zhuǎn))

針對接口

下面是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];                }

關(guān)于如何在PHP中實(shí)現(xiàn)依賴注入就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI