php – “阵列链接”的最佳解决方案
对于我的项目,我编写了一个小的配置类,从.ini文件加载其数据.它会覆盖magic __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(syntactic sugar)来访问所有配置变量.数组不是对象,而是“ – >”没有定义它,所以这只是失败. 我想到了一个解决方案,并想得到一些公众舆论: 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)也是一个好主意. 有什么建议,改进,评论吗? 解决方法
如果$this-> config数组的元素也是Config类的实例,那么它可以工作.
Zend Framework有一个类似的组件,他们称之为Zend_Config.你可以download来源并检查它们是如何实现它的.他们没有必要一直扩展ArrayObject. Zend_Registry类具有类似的用法,它确实扩展了ArrayObject. Zend_Registry的代码因此更简单一些. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |