1,987   DesignPatterns

1,当前只有一个依赖

class User{
        public function __construct(qq $qq){
            // 依赖注入 qq, 由外部实例化后注入
            $this->qq = $qq;
        }
    }
    $qq = new qq(); // 依赖注入 qq
    $user = new User($qq);

 

 

2,新增几个依赖

    class User{
        public function __construct(qq $qq, weibo $weibo, weixin $weixin){
            // 依赖注入 qq, weibo, weixin, 由外部实例化后注入 
            $this->qq = $qq;
            $this->weibo = $weibo;
            $this->weixin = $weixin;
        }
    }
    $qq = new qq(); // 新增依赖注入 qq
    $weibo = new weibo(); // 新增依赖注入 weibo
    $weixin = new weixin(); // 新增依赖注入 weixin
    $user = new User($qq, $weibo, $weixin);

 

 

3,发现新增依赖的时候,需要修改应用类的构造方法,怎么办呢?通过容器来管理依赖注入就可以解决了

    class User{
        protected $container;
        public function __construct(container $container){
            // 依赖注入 container, 里面包含了所有依赖
            $this->container = $container;
        }
        public function index(){
            $qq = $this->container->get('qq');
            $weibo = $this->container->get('weibo');
            $weixin = $this->container->get('weixin');
        }
    }

    $container = new container(); // 依赖注入的容器
    $container->set('qq',function(){
        return new qq(); // 新增依赖注入 qq
    });
    $container->set('weibo',function(){
        return new weibo(); // 新增依赖注入 weibo
    });
    $container->set('weixin',function(){
        return new weixin(); // 新增依赖注入 weixin
    });
    $user = new User($container);

通过容器管理依赖注入,所有依赖注册到容器中,应用类只需从容器中获取依赖;
当新增依赖时,只需注册到容器中,不用改动应用类的代码




Leave a Reply

Your email address will not be published. Required fields are marked *