THINKPHP5.1容器和闭包

容器用来更方便的管理类依赖及运行依赖注入。

依赖注入的类统一由容器进行管理,大多数情况下是在自动绑定并且实例化的。不过你可以随时进行手动绑定类到容器中

容器相当于依赖注入的管理程序

依赖注入会在类型约束时自动实例化传入的类

公共类Temp

<?php
namespace app\common;
class Temp
{
    // 公用属性,可以在URL中访问,protected和private不可以在外部访问
    public $name;
    // 构造方法,调用类时自动运行
    public function __construct($name = '默认名称')
    {
        $this->name = $name;
    }
    public function set($name)
    {
        $this->name = $name;
    }
    public function get()
    {
        return '当前方法为:'.__METHOD__.'当前属性为:'.$this->name;
    }


}

 将类和闭包注册到容器内

<?php
namespace app\demo\controller;
class Demo
{
    // 依赖注入
    public function bindClass()
    {
        // 容器相当于注册树模式
        // 将类注册到容器中,(将类挂到树上)
        \think\Container::set('temp','\app\common\Temp');
        // 实例化容器中的类并取出来使用,实例化类并从树上取下来用
        // 实例化同时会调用构造器进行初始化
        $temp = \think\Container::get('temp',['name'=>'容器']);
        return $temp->get();
    }
    // 闭包
    public function bindClosure()
    {
        // 将闭包注册到容器中
        \think\Container::set('domain',function ($domain){
            return $domain;
        });
        return \think\Container::get('domain',['domain'=>'www.baidu.com']);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38468437/article/details/82085454