解读 php容器模式-larave 、 Phalcon 等主流框架的百宝箱

项目地址

https://github.com/liaoshengping/phpNote/tree/master/basis/container/my_container
下载在本地 执行 index.php

效果

$app = new Application();
$app->db->test();

一般框架都有容器这个概念,当基础类多了,会很零散,所以得有一个东西能收纳这些功能。

零散的代码就好像在农村里生活一样,如果你对当地熟的话,其实也还好,自己知道就是比较麻烦一点,可能在去目的地的时候要花费一点时间。找你这个代码要一定的时间。

如果你在城里就不一样了, 有大型的商场里面啥都有,吃喝拉撒一条龙服务。只要进入了商场就非常多的指向标,小地图规划。这边提到的地图规划,就好像idea中的提示代码:
解读 php容器模式-larave 、 Phalcon 等主流框架的百宝箱_第1张图片
进入某个商场,参加具体某个项目,比如去餐厅,服务员会拿出具体的菜单给你过目:

解读 php容器模式-larave 、 Phalcon 等主流框架的百宝箱_第2张图片
解读 php容器模式-larave 、 Phalcon 等主流框架的百宝箱_第3张图片
可以根据不同用户加入属性,比如四川人很吃辣 spicy 属性就是加辣的
解读 php容器模式-larave 、 Phalcon 等主流框架的百宝箱_第4张图片
具体要用到这个属性的地方就是调取这个属性:
解读 php容器模式-larave 、 Phalcon 等主流框架的百宝箱_第5张图片
总的来说把一个大型的服务装进一个容器中,以这个容器为入口,程序的扩展性强,想让商场哪家倒闭就倒闭,新开一家就新开一家。

容器类

arrayAccess 赋予object 具有数组的功能



class Container implements \ArrayAccess
{
     
    private $values = array();
    public $register;

    public function serviceRegister(Provider $provider)
    {
     
        $provider->serviceProvider($this);
        return $this;
    }

    public function offsetExists($offset)
    {
     
        // TODO: Implement offsetExists() method.
    }
	//可能多次调用,所以把类储存在instances 中,防止反复实例
    public function offsetGet($offset)
    {
     
        if(isset($this->instances[$offset])){
     
            return $this->instances[$offset];
        }
        $raw = $this->values[$offset];
        $val = $this->values[$offset] = $raw($this);
        $this->instances[$offset] = $val;
        return $val;
    }



    public function offsetSet($offset, $value)
    {
     
        $this->values[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
     

    }
}

基础类

class Base extends Container
{
     
    protected $provider = [];

    public function __construct()
    {
     
        $provider_callback = function ($provider) {
     
            $this->serviceRegister(new $provider);
        };
        array_walk($this->provider, $provider_callback);//注册
    }

    public function __get($id)
    {
     
        return $this->offsetGet($id);

    }
}

服务

注释让开发效率翻倍

/**
 * Class Application
 * @property   Db db
 */
class Application extends Base
{
     
    protected $provider = [
        DbServiceProvider::class,
        //...其他服务
    ];

}

具体服务提供者

class DbServiceProvider implements Provider
{
     
    /**
     * 服务提供者
     * @param Container $container
     * @return mixed
     */
    public function serviceProvider(Container $container,array $values = array())
    {
     

        $container['db'] = function () {
     
            return new DB();
        };


    }
}



接口

interface Provider
{
     
    public function serviceProvider(Container $container);
}

实际功能类

class DB
{
     
    public function test()
    {
     
        echo 'laji';
    }
}

具体以仓库代码为准:
https://github.com/liaoshengping/phpNote/tree/master/basis/container/my_container

你可能感兴趣的:(php)