标签搜索
侧边栏壁纸
  • 累计撰写 96 篇文章
  • 累计收到 0 条评论

Lravel 容器实践

ManTou
2017-04-25 / 0 评论 / 0 阅读 / 正在检测是否收录...
<?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>';
0

评论

博主关闭了当前页面的评论