php依赖注入简介

全栈 shanhuhai 6238℃ 0评论

简介

依赖注入 Dependency Injection 简称 DI,目的是让代码耦合度降低,模块化程度高,让代码更易测试

什么是依赖

为什么会有依赖?因为我们为了模块化,把各种小功能都做成了一个模块,模块之间相互调用,这样就产生了依赖。

没有用依赖注入的情况

class Code{
    public function all(){
        echo 'code lists.';
    }
}
class User{
    public function show(){
        $code = new Code();
        echo $code->all();
    }
}

$user = new User();

$user->show();

这种情况下 , User 类依赖 Code类

使用依赖注入

<?php
class Code{
    public function all(){
        echo 'code lists.';
    }
}
class User{
    private $code ;

    public function __construct(Code $code){
        $this->code = $code;
    }
    public function show(){
        $this->code->all();
    }
}

$code = new Code();
$user = new User($code);

$user->show();

使用依赖注入的好处是显而易见的,我们通过参数了,让 Code 对象通过参数传到了 User 类中,而不是在 User 类中的方法中 实例化 Code类,从而将 Code 类和 User 类解耦

使用依赖注入容器来管理依赖

<?php
class Container
{
    private $s = array();

    function __set($k, $c)
    {
        $this->s[$k] = $c;
    }

    function __get($k)
    {
        return $this->s[$k]($this);
    }
}

class Code{
    public function all(){
        echo 'code lists.';
    }
}
class User{
    private $code ;

    public function __construct(Code $code){
        $this->code = $code;
    }
    public function show(){
        $this->code->all();
    }
}

$containter = new Container();
$containter->code = function(){
    return new Code();
};

$containter->user = function($c){
    return new User($c->code);
};

$user = $containter->user;
$user->show();

转载请注明:大后端 » php依赖注入简介

付费咨询
喜欢 (6)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址