一般一个框架会提供一种获取配置文件的操做类,该类的做用是,加载用户自定义配置文件,读取和设置配置文件等操做。php
咱们规定用户配置文件目录为 origin/app/conf
,在该目录下,config.php
是默认的配置文件,此外,还能够在该目录下建立其余配置文件,例如 db.php
,server.php
等,全部其余文件也会被自动加载。mysql
配置文件内容直接返回数组。示例redis
app/conf/config.php
sql
<?php return [ 'default' => [ 'controller' => 'index', 'action' => 'index', 'router' => 'querystring', ], 'debug' => true, 'cache' => 'redis', ];
app/conf/db.php
数组
<?php return [ 'mysql' => [ 'host' => '127.0.0.1', 'username' => '', 'password' => '', 'db' => '', 'port' => 3306, 'charset' => 'utf8', 'prefix' => '' ], 'redis' => [ 'scheme' => '', 'host' => '', 'port' => '', ] ];
经过 Config::get($key)
来获取配置。app
config.php
做为默认配置文件能够直接获取该配置文件内容,多维数组经过.
分隔,例如<?php Config::get('debug'); Config::get('default.route');
db.php
或其余自定义配置文件,须要添加文件名前缀,例如<?php Config::get('db.mysql.host'); Config::get('db.redis.scheme');
Config
类主要实现如下功能:框架
<?php namespace core; use dispatcher\Container; class Config extends Container { private $conf; public function __construct() { $conf = []; $path = APP_PATH.'/app/conf/'; foreach (scandir($path) as $file) { if (substr($file,-4) != '.php') { continue; } $filename = $path.$file; if ($file == 'config.php') { //1 $conf += require $filename; } else { //2 $k = explode('.', $file)[0]; $conf[$k] = require $filename; } } $this->conf = $conf; }
因为继承 Container
,构造函数只执行一次,所以在 __construct()
中加载配置文件能够避免重复加载。函数
除了 config.php
外的其余配置文件,须要用文件名做为 key
。ui
//1 protected function get($key = null, $default=null) { //2 if (empty($key)) { return $this->conf; } //3 if (strpos($key, '.')) { $conf = $this->conf; foreach (explode('.', $key) as $k) { $conf = $conf[$k] ?? $default; } return $conf; } //4 return $this->conf[$key] ?? $default; }
::
执行方法时,该方法须要声明为 protected
,如 Config::get($key);
。$key
为空,则返回全部配置。.
来解析多维数组配置。