对于我的项目,我编写了一个从 .ini 文件加载其数据的小型配置类。它覆盖了神奇的 __get() 方法,以提供对(只读)配置值的简化访问。
示例 config.ini.php:
;<?php exit; ?>
[General]
auth = 1
user = "halfdan"
[Database]
host = "127.0.0.1"
我的配置类(单例模式 - 此处简化)如下所示:
class Config {
protected $config = array();
protected function __construct($file) {
// Preserve sections
$this->config = parse_ini_file($file, TRUE);
}
public function __get($name) {
return $this->config[$name];
}
}
加载配置将创建一个数组结构,如下所示:
array(
"General" => array(
"auth" => 1,
"user" => "halfdan"
),
"Database" => array(
"host" => "127.0.0.1"
)
)
可以通过执行访问数组的第一级,使用 访问Config::getInstance()->General
值Config::getInstance()->General['user']
。我真正想要的是能够通过执行Config::getInstance()->General->user
(语法糖)访问所有配置变量。该数组不是一个对象,并且没有在其上定义“->”,所以这只是失败了。
我想到了一个解决方案,并希望得到一些公众意见:
class Config {
[..]
public function __get($name) {
if(is_array($this->config[$name])) {
return new ConfigArray($this->config[$name]);
} else {
return $this->config[$name];
}
}
}
class ConfigArray {
protected $config;
public function __construct($array) {
$this->config = $array;
}
public function __get($name) {
if(is_array($this->config[$name])) {
return new ConfigArray($this->config[$name]);
} else {
return $this->config[$name];
}
}
}
这将允许我链接我的配置访问。由于我使用的是 PHP 5.3,因此让 ConfigArray 扩展ArrayObject也是一个好主意(在 5.3 中默认激活 SPL)。
有什么建议、改进、意见吗?