Lravel 容器实践

作者: 分类: laravel,php 时间: 2017-04-25 评论: 暂无评论
<?php
interface Model{
    public function run();
}


class SuperMan{
    public $model;
    public function __construct(Model $mode)
    {
        $this->model=$mode;
    }
}
class XPower implements Model{
    public function run(){
        echo '发射X-射线';
    }
}



class Container{
    protected $binds;//绑定
    protected $instances;//实例化

    /**
     * 绑定模块
     * @param $abstract  模块关键字
     * @param $concrete  闭包函数 或 实例
     */
    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);
        return call_user_func_array($this->binds[$abstract],$parameters);
    }
}

$container=new Container(); //模块工厂
// 工厂初始化
$container->bind('superman', function($container, $moduleName) {
    return new SuperMan($container->make($moduleName));
});
$container->bind('x-power',function($container){
    return new XPower;
});
echo '<pre>';
$superman = $container->make('superman', ['x-power']);
var_dump($superman);
echo '</pre>';