Inyección y contenedores de dependencia DI

Ventajas: reducir la relación entre clases y clases
Contenedor:
1. Reducir el acoplamiento entre clases
2. Darse cuenta de la carga diferida (qué clase se necesita para crear qué clase)
3. Fácil de administrar

<?php
//轮胎类=》汽车类
class LunTai
{
    function roll()
    {
        echo "轮胎在转动\n";
    }
}

//class BMW
//{
//    public function run()
//    {
//        $luntai = new LunTai();
//        $luntai->roll();
//        echo "开着宝马玩\n";
//    }
//}
//普通方式
//$bmw = new BMW();
//$bmw->run();

//依赖注入
class BMW
{
    protected $luntai;
    function __construct($luntai)
    {
        $this->luntai = $luntai;
    }

    function run()
    {
        $this->luntai->roll();
        echo "开着宝马玩\n";
    }
}
//
//$luntai = new LunTai();
//$bmw = new BMW($luntai);
//$bmw->run();

//容器
class Container
{
    //存放所绑定的类
    static $register = [];

    //绑定函数
    static function bind($className,Closure $closure)
    {
        self::$register[$className] = $closure;
    }

    //创建对象函数
    static function make($name)
    {
        $closure = self::$register[$name];
        return $closure();
    }
}

Container::bind('LunTai',function (){
    return new LunTai();
});
Container::bind('BMW',function (){
    return new BMW(Container::make('LunTai'));
});


$bmw = Container::make('BMW');
$bmw->run();


Supongo que te gusta

Origin blog.csdn.net/kevlin_V/article/details/104032165
Recomendado
Clasificación