依赖注入类 php,php依赖注入简介

简介

依赖注入 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类

使用依赖注入

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 类解耦

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

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();

喜欢 (5)or分享 (0)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值