所以,我正在考虑多种存储配置数据的方式。我相信已经将其缩小到了3种方式:
1.仅使用简单变量
$config = array(
"database" => array(
"host" => "localhost",
"user" => "root",
"pass" => "",
"database" => "test"
)
);
echo $config['database']['host'];
我认为这个太易变了,配置选项不应该被改变。
修改后的标准类。
class stdDataClass {
// Holds the Data in a Private Array, so it cannot be changed afterwards.
private $data = array();
public function __construct($data)
{
// ......
$this->data = $data;
// .....
}
// Returns the Requested Key
public function __get($key)
{
return $this->data[$key];
}
// Throws an Error as you cannot change the data.
public function __set($key, $value)
{
throw new Exception("Tried to Set Static Variable");
}
}
$config = new stdStaticClass($config_options);
echo $config->database['host'];
基本上,它所做的就是将上述数组封装到一个对象中,并确保该对象不能被更改。
或者是一个静态类
class AppConfig{
public static function getDatabaseInfo()
{
return array(
"host" => "localhost",
"user" => "root",
"pass" => "",
"database" => "test"
);
}
// .. etc ...
}
$config = AppConfig::getDatabaseInfo();
echo $config['host'];
这提供了终极不可变性,但这也意味着每当我想更改数据时,我都必须手动编辑类。
你认为上述哪种方式最适合存储配置选项?或者有更好的方法吗?