php依赖注入和控制反转的区别,PHP 依赖注入(DI)和控制反转(IoC)简单理解

interface BehaviorInterface { //接口

public function behavior_func();

}

class SleepInterface implements BehaviorInterface {

public function behavior_func() {

echo "this is sleep_func"."
";

}

}

class EatInterface implements BehaviorInterface {

public function behavior_func() {

echo "this is eat_func"."
";

}

}

class BehaviorClass {

protected $module;

public function __construct(BehaviorInterface $module) {

$this->module = $module;

}

public function behavior_func() {

$this->module->behavior_func();

}

}

class Container { //容器

protected $binds;

public function bind($abstract,Closure $concrete) {

$this->binds[$abstract] = $concrete;

}

public function make($abstract, $parameters = []) {

array_unshift($parameters, $this);

return call_user_func_array($this->binds[$abstract], $parameters);

}

}

// 创建一个容器(后面称作超级工厂)

$container = new Container;

// 向该 超级工厂添加行为的生产脚本

$container->bind('BehaviorClass', function($container, $moduleName) {

return new BehaviorClass($container->make($moduleName));

});

// 向该 超级工厂添加模组的生产脚本

$container->bind('EatInterface', function($container) {

return new EatInterface;

});

// 同上

$container->bind('SleepInterface', function($container) {

return new SleepInterface;

});

// 开始启动生产

//最主要是call_user_func_array 要先理解 最主要是call_user_func_array

/** make方法 大概理解是 调用绑定好的BehaviorClass方法(bind) 然后把EatInterface传入调用call_user_func_array

(即调用return new BehaviorClass($container->make($moduleName))这个方法)

(这里的$moduleName为了形象一点也指EatInterface) 在传入的同时其实是先进了里面的$container->make($moduleName)方法

用call_user_func_array把EatInterface先给new了 接着才new外面的BehaviorClass(EatInterface)

最后返回一个有EatInterface模块的BehaviorClass类

同理 $b_2 $b_3也是这样 */

$b_1 = $container->make('BehaviorClass', ['EatInterface']);

$b_2 = $container->make('BehaviorClass', ['SleepInterface']);

$b_3 = $container->make('BehaviorClass', ['EatInterface']);

// 调用

echo "
";

$b_1->behavior_func();

$b_2->behavior_func();

标签:function,container,DI,make,BehaviorClass,func,EatInterface,PHP,IoC

来源: https://www.cnblogs.com/applystyle/p/13585971.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值