一,依赖注入 与 控制反转

依赖注入与控制反转其实说的是同一种编程思想,其目的是为了解耦和。我们都知道程序耦合度越紧,在需求变更后,一个模块的修改往往会导致其他功能模块的变化,不利于后期的开发与维护。

容器类

class Container{
    // 绑定闭包
    private $binds = [];
    // 绑定实例
    private $instances = [];
    
    /**
     * @param $abstract 容器绑定的类或者闭合函数名称
     * @param $concrete 具体绑定的类或者闭合函数
     */
    public function bind($abstract, $concrete){
        if($concrete instanceof \Closure){
            $this->binds[$abstract] = $concrete;
        }else{
            $this->instances[$abstract] = $cocrete;
        }
    }
    
    
    /**
     * @param $abstract 容器绑定的类或者闭合函数名称
     * @param $param 实例化该类需要的参数(一般为依赖的类)
     */
    public function make($abstract, $params = []){
        if(isset($this->instances[$abstract])){
            return $this->instances[$abstract];
        }
        array_unshift($param, $this);
        return call_user_func_array($this->binds[$abstract],$param);
    }
}

数据库操作类

class DB{

    private $driver;

    public function __construct(DBDriver $driver)
    {
        $this->driver = $driver;
    }

    public function query(){
        echo $this->driver->query();
    }
}

驱动接口

interface DBDriver{

    public function query();
}

Mysql驱动

class Mysql implements DBDriver {

    public function query(){
        return __METHOD__;
    }
}

手动依赖注入

$di = new Container();

$di->bind('Mysql',function (){
   return new Mysql();
});

$di->bind('DB',function ($di,$driver){
    return new DB($di->make($driver));
});

$db = $di->make('DB',['Mysql']);

$db->query();

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐