PHP如何實現依賴注入
摘要: 控制反轉(Inversion of Control,英文縮寫為IoC)是框架的重要特征??刂品崔D(IOC)是一種思想,依賴注入(DI)是實施這種思想的方法。
高層模塊不應該依賴于底層模塊,兩個都應該依賴抽象。
抽象不應該依賴于細節,細節應該依賴于抽象。
首先,我們來看一段代碼:
- 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 的方式在內部進行,EchoT類嚴重依賴于類A。每當類A變化時,EchoT類也得進行變化。
我們優化一下代碼
- class EchoT {
- protected $t;
- public function __construct($t) //構造器注入由構造器注入到其中
- {
- $this->t = $t;
- }
可以看到,這樣做的話。很大程序上,我們對程序進行了解耦。類A無論你如何變動,EchoT類是不需要變動的。不再依賴于A。但是新問題又來了,我們現在只有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) //構造器注入由構造器注入到其中
- {
- $this->t = $t;
- }
- public function echo(){
- $this->t->echo();
- }
- }
將T抽象出為接口,這樣,EchoT類中的echo方法變成一個抽象的方法,不到運行那一刻,不知道他們的Method方式是怎么實現的。
工廠
- function getT($str) {
- if(class_exists($str)){
- return new $str();
- }
- }
T要使用哪個是不明確的,因此,我們可以將其工廠化?!究瓷先ズ芎唵?,在DI實際上有體現】
DI(重點來了)
首先,我們看一下PHP的psr規范。
http://www.php-fig.org/psr/psr-11/
官方定義的接口
Psr\Container\ContainerInterface
包含兩個方法
function get($id);
function has($id);
仔細看上面的工廠,是不是和get($id)很一致,PHP官方將其定義為容器(Container,我個人理解,就是一個復雜的工廠)
dependency injection container
依賴注入容器
- namespace Core;
- use Psr\Container\ContainerInterface;
- class Container implements ContainerInterface
- {
- protected $instance = [];//對象存儲的數組
- 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);
- }
- // 檢查類是否可實例化, 排除抽象類abstract和對象接口interface
- if (!$reflector->isInstantiable()) {
- throw new \Exception("Can't instantiate ".$className);
- }
- /** @var \ReflectionMethod $constructor 獲取類的構造函數 */
- $constructor = $reflector->getConstructor();
- // 若無構造函數,直接實例化并返回
- if (is_null($constructor)) {
- return new $className;
- }
- // 取構造函數參數,通過 ReflectionParameter 數組返回參數列表
- $parameters = $constructor->getParameters();
- // 遞歸解析構造函數的參數
- $dependencies = $this->getDependencies($parameters);
- // 創建一個類的新實例,給出的參數將傳遞到類的構造函數。
- $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)) {
- // 是變量,有默認值則設置默認值
- $dependencies[] = $this->resolveNonClass($parameter);
- } else {
- // 是一個類,遞歸解析
- $dependencies[] = $this->build($dependency->name);
- }
- }
- return $dependencies;
- }
- /**
- * @param \ReflectionParameter $parameter
- * @return mixed
- * @throws \Exception
- */
- public function resolveNonClass(\ReflectionParameter $parameter)
- {
- // 有默認值則返回默認值
- if ($parameter->isDefaultValueAvailable()) {
- return $parameter->getDefaultValue();
- }
- throw new \Exception($parameter->getName().' must be not null');
- }
- /**
- * 參照psr-autoload規范
- * @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'); //實現的PSR規范的異常
- }
- public function has($id)
- {
- return isset($this->instance[$id]) ? true : false;
- }
- }
使用示例
- $container = new Container('../');//假設這是路徑
- $echoT = $container->get(\Test\EchoT::class); //假設echoT類的命名空間是\Test
- $echoT->echo();
這個時候,會出現一個問題:
- // 檢查類是否可實例化, 排除抽象類abstract和對象接口interface
- if (!$reflector->isInstantiable()) {
- throw new \Exception("Can't instantiate ".$className);
因為接口T是無法實例化的,所以,一般在程序內,我們都加上別名(參照laravel框架)
- $container->alisa(\Test\T::class,\Test\T\A::class); //指定接口T使用類A(控制反轉)
針對接口
下面是alias方法
- public function alias(string $key, $class, bool $singleton = true)
- {
- if($singleton) {
- $this->singleton[] = $class;
- }
- $this->aliases[$key] = $class;
- return $this;
- }
- //同時,我們需要在build的時候進行判斷是否為別名
- 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];
- }
就此,一個簡單的PHP容器就實現了。