打赏

注册树模式

注册树模式(laravel框架的服务容器用到注册树模型)

<?php
//注册树模式
class Container
{
    //用于存储实例化的对象或者类的命名空间
    private $bindings = [];

    //注册对象到$bindings数组里面,进行存储
    public function bind($abstract, $concrete = null,$shared = null)
    {
        $this->bindings[$abstract]['concrete'] = $concrete;
        $this->bindings[$abstract]['shared'] = $shared;
    }

    public function make($abstract,$parameters = [])
    {
        $object = $this->bindings[$abstract]['concrete'];
        if ($object instanceof \Closure){
            return $object();
        }

        if(!is_object($object)){
            return new $object(...$parameters);
        }
    }

    public function delete($abstract){
        unset($this->bindings[$abstract]);
    }
}

class A
{
    public function run()
    {
        echo '这是A类'."<br/>";
    }
}

class B
{
    public function run()
    {
        echo '这是B类'."<br/>";
    }
}

$containter = new Container();
$containter->bind('a',function(){
    return new A();
});
$containter->make('a')->run();

$containter->bind('b',function(){
    return new B();
});
$containter->make('b')->run();

 

 

posted on 2021-08-19 22:27  头大的冯冯  阅读(64)  评论(0编辑  收藏  举报

导航