容器
参考:
转载自:Laravel 服务容器实例教程 —— 深入理解控制反转(IoC)和依赖注入(DI)
转载自:如何理解laravel的IOC
laravel文章里面的容器代码有点问题,下面的评论也已经改过来了,这个下面的代码实测正常,里面的闭包不好理解,搅和了半天
echo "<pre/>";
class Superman
{
    public $module;
    public function __construct(SuperModuleInterface $module,$name)
    {
        $this->module->$name = $module;
    }
}
interface SuperModuleInterface
{
    /**
     * 超能力激活方法
     *
     * 任何一个超能力都得有该方法,并拥有一个参数
     *@param array $target 针对目标,可以是一个或多个,自己或他人
     */
    public function activate(array $target);
}
class XPower implements SuperModuleInterface
{
    public function activate(array $target)
    {
        echo "这个是xpower";
    }
}
class Container
{
    public $binds;
    public $instances;
    public function bind($abstract, $concrete)
    {
        if ($concrete instanceof Closure) {
            $this->binds[$abstract] = $concrete;
        } else {
            $this->instances[$abstract] = $concrete;
        }
    }
    public function make($abstract, $parameters = [])
    {
        if (isset($this->instances[$abstract])) {
            return $this->instances[$abstract];
        }
        array_unshift($parameters, $this);
        $concrete = $this->binds[$abstract];
        var_dump($concrete);
        //return call_user_func_array($this->binds[$abstract], $parameters);
        $this->instances[$abstract] = call_user_func_array($concrete, $parameters);
        return $this->instances[$abstract];
    }
}
$container = new Container;
// 向该 超级工厂添加超人的生产脚本
$container->bind('superman', function($container, $moduleName) {
    return new Superman($container->make($moduleName),$moduleName);
});
$container->bind('xpower', function($container) {
    return new XPower;
});
$superman = $container->make('superman',['xpower']);
var_dump($superman);



