Home  >  Article  >  PHP Framework  >  Detailed explanation of Laravel—IOC container

Detailed explanation of Laravel—IOC container

藏色散人
藏色散人forward
2020-12-21 09:13:352301browse

The following tutorial column of Laravel Framework will give you a detailed explanation of Laravel-IOC container. I hope it will be helpful to friends in need!

Detailed explanation of Laravel—IOC container

1. Dependency

IOC (inversion of controller) is called inversion of control mode, also known as (dependency injection) dependency injection mode . To understand the concept of dependency injection, we first understand what dependencies

//支付宝支付
class Alipay {
      public function __construct(){}

      public function pay()
      {
          echo 'pay bill by alipay';
      }
}
//微信支付
class Wechatpay {
      public function __construct(){}

      public function pay()
      {
          echo 'pay bill by wechatpay';
      }
}
//银联支付
class Unionpay{
      public function __construct(){}

      public function pay()
      {
          echo 'pay bill by unionpay';
      }
}

//支付账单
class PayBill {

      private $payMethod;

      public function __construct( )
      {
          $this->payMethod= new Alipay ();
      }

      public function  payMyBill()
      {
           $this->payMethod->pay();
      }
}


$pb = new PayBill ();
$pb->payMyBill();

Through the above code, we know that when we create an instance of class PayBill, the constructor of PayBill contains { $this->payMethod = new Alipay (); }, that is, a class Alipay is instantiated. At this time, dependency is generated. It can be understood that when I want to pay with Alipay, I first need to obtain an instance of Alipay, or understand In order to obtain Alipay functional support. When we finish using the new keyword, the dependency has actually been resolved because we have obtained an instance of Alipay.

In fact, before I knew the concept of ioc, my Most of the code is in this pattern~ _ ~. What is the problem with this? To put it simply, for example, what should I do when I want to use WeChat instead of Alipay? What you can do is to modify the constructor of Payment. The code instantiates a WeChat payment Wechatpay.

If our program is not very big, we may not feel anything, but when your code is very complex and huge, if our needs often change , then modifying the code becomes very troublesome. Therefore, the idea of ​​​​ioc is not to use new to instantiate and solve dependencies in class Payment, but to turn it into an external responsibility. To put it simply, there is no new step internally, and the payment can be obtained through dependency injection. Example.

2. Dependency injection

We know what dependency means, so what does dependency injection mean? Let’s expand the above code

//支付类接口
interface Pay
{
    public function pay();
}


//支付宝支付
class Alipay implements Pay {
      public function __construct(){}

      public function pay()
      {
          echo 'pay bill by alipay';
      }
}
//微信支付
class Wechatpay implements Pay  {
      public function __construct(){}

      public function pay()
      {
          echo 'pay bill by wechatpay';
      }
}
//银联支付
class Unionpay implements Pay  {
      public function __construct(){}

      public function pay()
      {
          echo 'pay bill by unionpay';
      }
}

//付款
class PayBill {

      private $payMethod;

      public function __construct( Pay $payMethod)
      {
          $this->payMethod= $payMethod;
      }

      public function  payMyBill()
      {
           $this->payMethod->pay();
      }
}

//生成依赖
$payMethod =  new Alipay();
//注入依赖
$pb = new PayBill( $payMethod );
$pb->payMyBill();

above In the code, compared with the previous one, we add a Pay interface, and then all payment methods inherit this interface and implement the pay function. You may ask why an interface is used, which we will talk about later.

When we instantiate PayBill, we first instantiate an Alipay. This step is to generate the dependency. Then we need to inject this dependency into the PayBill instance. Through the code, we You can see { $pb = new PayBill( payMethod ); }, we injected this dependency into PayBill through the constructor. In this way, the PayBill instance $pb has the ability to pay with Alipay.

Inject the instance of class Alipay through the constructor to instantiate a class PayBill. Our injection here is manual injection, not automatic. The Laravel framework implementation is automatic injection.

3. Reflection

Before introducing the IOC container, let us first understand the concept of reflection (reflection), because the IOC container is also implemented through reflection. I copied a paragraph from the Internet to explain what reflection means

"Reflection" refers to extending the analysis of PHP programs in the running state of PHP, exporting or extracting detailed information about classes, methods, properties, parameters, etc., including comments. This dynamically obtained information and dynamically calling methods of objects The function is called reflection API. Reflection is an API for manipulating meta-models in the object-oriented paradigm. It is very powerful and can help us build complex and scalable applications. Its uses are such as: automatically loading plug-ins, automatically generating documents, and even usable To expand the PHP language"

Give a simple example

class B{

}


class A {

    public function __construct(B $args)
    {
    }

    public function dosomething()
    {
        echo 'Hello world';
    }
}

//建立class A 的反射
$reflection = new ReflectionClass('A');

$b = new B();

//获取class A 的实例
$instance = $reflection ->newInstanceArgs( [ $b ]);

$instance->dosomething(); //输出 ‘Hellow World’

$constructor = $reflection->getConstructor();//获取class A 的构造函数

$dependencies = $constructor->getParameters();//获取class A 的依赖类

dump($constructor);

dump($dependencies);

The $constructor and $dependencies obtained by dumping are as follows

//constructor
ReflectionMethod {#351 
        +name: "__construct" 
        +class: "A" 
        parameters: array:1 [] 
        extra: array:3 [] 
        modifiers: "public"
}

//$dependencies
array:1 [
        0 => ReflectionParameter {#352 
         +name: "args"
          position: 0
          typeHint: "B"
      }
]

Through the above code we can Obtain the constructor of class A and the classes that the constructor depends on. Here we rely on a quantity named 'args', and through TypeHint we can know that it is of type Class B; the reflection mechanism allows me to parse a class , you can obtain the attributes, methods, constructors, and parameters required by the constructor in a class. Only with this can we realize Laravel's IOC container.

4.IOC container

Next, we will introduce the concept of Laravel's IOC service container. In the laravel framework, the service container is the entire The core of laravel, it provides the configuration and invocation of the entire system functions and services. A container is literally a thing that holds things, such as a refrigerator. When we need the contents of the refrigerator, we can just take it directly from it. Service container It can also be understood this way. When the program starts running, we put or register (bind) some services we need into the container, and when I need them, just take them out (make). The bind mentioned above and make are the two actions of registration and removal.

5. IOC 容器代码

好了,说了这么多,下面要上一段容器的代码了. 下面这段代码不是laravel 的源码, 而是来自一本书《laravel 框架关键技术解析》. 这段代码很好的还原了laravel 的服务容器的核心思想. 代码有点长, 小伙伴们要耐心看. 当然小伙伴完全可以试着运行一下这段代码,然后调试一下,这样会更有助于理解.

<?php 

//容器类装实例或提供实例的回调函数
class Container {

    //用于装提供实例的回调函数,真正的容器还会装实例等其他内容
    //从而实现单例等高级功能
    protected $bindings = [];

    //绑定接口和生成相应实例的回调函数
    public function bind($abstract, $concrete=null, $shared=false) {
        
        //如果提供的参数不是回调函数,则产生默认的回调函数
        if(!$concrete instanceof Closure) {
            $concrete = $this->getClosure($abstract, $concrete);
        }
        
        $this->bindings[$abstract] = compact(&#39;concrete&#39;, &#39;shared&#39;);
    }

    //默认生成实例的回调函数
    protected function getClosure($abstract, $concrete) {
        
        return function($c) use ($abstract, $concrete) {
            $method = ($abstract == $concrete) ? &#39;build&#39; : &#39;make&#39;;
            return $c->$method($concrete);
        };
        
    }

    public function make($abstract) {
        $concrete = $this->getConcrete($abstract);

        if($this->isBuildable($concrete, $abstract)) {
            $object = $this->build($concrete);
        } else {
            $object = $this->make($concrete);
        }
        
        return $object;
    }

    protected function isBuildable($concrete, $abstract) {
        return $concrete === $abstract || $concrete instanceof Closure;
    }

    //获取绑定的回调函数
    protected function getConcrete($abstract) {
        if(!isset($this->bindings[$abstract])) {
            return $abstract;
        }

        return $this->bindings[$abstract][&#39;concrete&#39;];
    }

    //实例化对象
    public function build($concrete) {

        if($concrete instanceof Closure) {
            return $concrete($this);
        }

        $reflector = new ReflectionClass($concrete);
        if(!$reflector->isInstantiable()) {
            echo $message = "Target [$concrete] is not instantiable";
        }

        $constructor = $reflector->getConstructor();
        if(is_null($constructor)) {
            return new $concrete;
        }

        $dependencies = $constructor->getParameters();
        $instances = $this->getDependencies($dependencies);

        return $reflector->newInstanceArgs($instances);
    }

    //解决通过反射机制实例化对象时的依赖
    protected function getDependencies($parameters) {
        $dependencies = [];
        foreach($parameters as $parameter) {
            $dependency = $parameter->getClass();
            if(is_null($dependency)) {
                $dependencies[] = NULL;
            } else {
                $dependencies[] = $this->resolveClass($parameter);
            }
        }

        return (array)$dependencies;
    }

    protected function resolveClass(ReflectionParameter $parameter) {
        return $this->make($parameter->getClass()->name);
    }

}

上面的代码就生成了一个容器,下面是如何使用容器

$app = new Container();
$app->bind("Pay", "Alipay");//Pay 为接口, Alipay 是 class Alipay
$app->bind("tryToPayMyBill", "PayBill"); //tryToPayMyBill可以当做是Class PayBill 的服务别名

//通过字符解析,或得到了Class PayBill 的实例
$paybill = $app->make("tryToPayMyBill"); 

//因为之前已经把Pay 接口绑定为了 Alipay,所以调用pay 方法的话会显示 &#39;pay bill by alipay &#39;
$paybill->payMyBill();

当我们实例化一个Container得到 $app 后, 我们就可以向其中填充东西了

$app->bind("Pay", "Alipay");
$app->bind("tryToPayMyBill", "PayBill");

当执行完这两行绑定码后, $app 里面的属性 $bindings 就已经有了array 值,是啥样的呢,我们来看下

array:2 [
 "App\Http\Controllers\Pay" => array:2 [
     "concrete" => Closure {#355 
       class: "App\Http\Controllers\Container" 
       this:Container{[#354](http://127.0.0.4/ioc#sf-dump-254248394-ref2354) …} 
       parameters: array:1 [
         "$c" => []
       ] 
       use: array:2 [
         "$abstract" => "App\Http\Controllers\Pay"
        "$concrete" => "App\Http\Controllers\Alipay"
       ] 
       file: "C:\project\test\app\Http\Controllers\IOCController.php" line:       "119 to 122"
   } 
   "shared" => false 
 ]

"tryToPayMyBill" => array:2 [
     "concrete" => Closure {#359 
         class: "App\Http\Controllers\Container" 
         this:Container{[#354](http://127.0.0.4/ioc#sf-dump-254248394-ref2354) …} 
         parameters: array:1 [
               "$c" => []
         ] 
         use: array:2 [
               "$abstract" => "tryToPayMyBill" 
               "$concrete" => "\App\Http\Controllers\PayBill"
         ] 
         file: "C:\project\test\app\Http\Controllers\IOCController.php" line: "119 to 122"
   } 
     "shared" => false 
 ]
]

当执行 $paybill = $app->make(“tryToPayMyBill”); 的时候, 程序就会用make方法通过闭包函数的回调开始解析了.

解析’tryToPayBill’ 这个字符串, 程序通过闭包函数 和build方法会得到 ‘PayBill’ 这个字符串,该字符串保存在$concrete 上. 这个是第一步. 然后程序还会以类似于递归方式 将$concrete 传入 build() 方法. 这个时候build里面就获取了$concrete = ‘PayBill’. 这个时候反射就派上了用场, 大家有没有发现,PayBill 不就是 class PayBill 吗? 然后在通过反射的方法ReflectionClass(‘PayBill’) 获取PayBill 的实例. 之后通过getConstructor(),和getParameters() 等方法知道了 Class PayBill 和 接口Pay 存在依赖

//$constructor = $reflector->getConstructor();
ReflectionMethod {#374 
    +name: "__construct" 
    +class: "App\Http\Controllers\PayBill" 
    parameters: array:1 [
          "$payMethod" => ReflectionParameter {#371 
              +name: "payMethod" 
              position: 0 typeHint: "App\Http\Controllers\Pay"
          }
    ]
     extra: array:3 [
          "file" => "C:\project\test\app\Http\Controllers\IOCController.php"
          "line" => "83 to 86" 
          "isUserDefined" => true 
      ] 
    modifiers: "public"
}


//$dependencies = $constructor->getParameters();
array:1 [
    0 => ReflectionParameter {#370 
        +name: "payMethod" 
        position: 0 
        typeHint: "App\Http\Controllers\Pay"
        }
]

接着,我们知道了有’Pay’这个依赖之后呢,我们要做的就是解决这个依赖,通过 getDependencies($parameters), 和 resolveClass(ReflectionParameter $parameter) ,还有之前的绑定$app->bind(“Pay”, “Alipay”); 在build 一次的时候,通过 return new $concrete;到这里我们得到了这个Alipay 的实例

        if(is_null($constructor)) {
            return new $concrete;
        }

到这里我们总算结局了这个依赖, 这个依赖的结果就是实例化了一个 Alipay. 到这里还没结束

        $instances = $this->getDependencies($dependencies);

上面的$instances 数组只有一个element 那就是 Alipay 实例

  array:1 [0 =>Alipay
      {#380}
 ]

最终通过 newInstanceArgs() 方法, 我们获取到了 PayBill 的实例。

 return $reflector->newInstanceArgs($instances);

到这里整个流程就结束了, 我们通过 bind 方式绑定了一些依赖关系, 然后通过make 方法 获取到到我们想要的实例. 在make中有牵扯到了闭包函数,反射等概念.

好了,当我们把容器的概念理解了之后,我们就可以理解下为什么要用接口这个问题了. 如果说我不想用支付宝支付,我要用微信支付怎么办,too easy.

$app->bind("Pay", "Wechatpay");
$app->bind("tryToPayMyBill", "PayBill");
$paybill = $app->make("tryToPayMyBill"); 
$paybill->payMyBill();

是不是很简单呢, 只要把绑定从’Alipay’ 改成 ‘Wechatpay’ 就行了,其他的都不用改. 这就是为什么我们要用接口. 只要你的支付方式继承了pay 这个接口,并且实现pay 这个方法,我们就能够通过绑定正常的使用. 这样我们的程序就非常容易被拓展,因为以后可能会出现成百上千种的支付方式.

好了,到这里不知道小伙伴有没有理解呢,我建议大家可以试着运行下这些代码, 这样理解起来会更快.同时推荐大家去看看 《laravel 框架关键技术解析》这本书,写的还是不错的.

The above is the detailed content of Detailed explanation of Laravel—IOC container. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete