ArrayAccess之像laravel框架一样读取配置文件

在各种框架中,都可以看见它们很方便的读取配置文件,就比如ThinkPHP,laravel。它们的配置文件的格式类似如下:

<?php
return [
    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
    ]
];

然后一个函数config('文件名.connections.mysql.driver')就可以读取值。这靠得是我们PHP内置的预定义接口——ArrayAccess。

只要你的类实现了这个预定义接口,便可以使用数组的方式访问类。这样说也许不好理解,让我们来实现像laravel一样读取配置文件吧。

<?php

class Config implements ArrayAccess
{
    private $path;
    private $config = [];
    private static $install;

    private function __construct()
    {
        //定义配置文件处于当前目录下的config文件夹中
        $this->path = __DIR__.'/config/';
    }

    //返回单例
    public static function install()
    {
        if (! self::$install) {
            self::$install = new self();
        }
        return self::$install;
    }

    public function offsetExists($offset)
    {
        return isset($this->config[$offset]);
    }

    public function offsetGet($offset)
    {
        if (empty($this->config[$offset])) {
            $this->config[$offset] = require $this->path.$offset.".php";
        }
        return $this->config[$offset];
    }

    //你的配置肯定不想被外部设置或者删除
    public function offsetSet($offset, $value)
    {
        throw new Exception('could not set');
    }

    public function offsetUnset($offset)
    {
        throw new Exception('could not unset');
    }
}

function config($keys)
{
    $config = Config::install();
    $keysArray = explode('.', $keys);
    $config = $config[$keysArray[0]];
    unset($keysArray[0]);
    foreach ($keysArray as $key) {
        $config = $config[$key];
    }
    return $config;
}
echo config('config.debug');

在当前文件夹中建立config文件夹,用config函数便可以读取各种配置了。 

posted @ 2018-03-31 00:50  TianJiankun  阅读(336)  评论(0编辑  收藏  举报