PHP 依赖注入(DI)和控制反转(IoC)简单理解
<?php
interface BehaviorInterface { //接口
public function behavior_func();
}
class SleepInterface implements BehaviorInterface {
public function behavior_func() {
echo "this is sleep_func"."<br>";
}
}
class EatInterface implements BehaviorInterface {
public function behavior_func() {
echo "this is eat_func"."<br>";
}
}
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 "<br>";
$b_1->behavior_func();
$b_2->behavior_func();