我想覆盖Zend_Config方法__set($ name,$ value),但我遇到同样的问题。
$ name - 返回覆盖配置值的当前键,例如:
$this->config->something->other->more = 'crazy variable'; // $name in __set() will return 'more'
因为config中的每个节点都是新的Zend_Config()类。
那么 - 如何从覆盖的__set()metod访问父节点名称?
我的申请: 我必须在控制器中覆盖相同的配置值,但是为了控制覆盖,并且不允许覆盖其他配置变量,我想在相同的其他配置变量中指定一个覆盖允许配置密钥的树形数组。
答案 0 :(得分:3)
除非您在施工期间将$ allowModifications设置为true,否则Zend_Config是只读的。
来自Zend_Config_Ini::__constructor()
docblock: -
/** The $options parameter may be provided as either a boolean or an array.
* If provided as a boolean, this sets the $allowModifications option of
* Zend_Config. If provided as an array, there are three configuration
* directives that may be set. For example:
*
* $options = array(
* 'allowModifications' => false,
* 'nestSeparator' => ':',
* 'skipExtends' => false,
* );
*/
public function __construct($filename, $section = null, $options = false)
这意味着您需要执行以下操作: -
$inifile = APPLICATION_PATH . '/configs/application.ini';
$section = 'production';
$allowModifications = true;
$config = new Zend_Config_ini($inifile, $section, $allowModifications);
$config->resources->db->params->username = 'test';
var_dump($config->resources->db->params->username);
结果
字符串'test'(长度= 4)
回复评论
在这种情况下,您可以简单地扩展Zend_Config_Ini并覆盖__construct()
和__set()
方法,如下所示: -
class Application_Model_Config extends Zend_Config_Ini
{
private $allowed = array();
public function __construct($filename, $section = null, $options = false) {
$this->allowed = array(
'list',
'of',
'allowed',
'variables'
);
parent::__construct($filename, $section, $options);
}
public function __set($name, $value) {
if(in_array($name, $this->allowed)){
$this->_allowModifications = true;
parent::__set($name, $value);
$this->setReadOnly();
} else { parent::__set($name, $value);} //will raise exception as expected.
}
}
答案 1 :(得分:0)
总是有另一种方式:)
$arrSettings = $oConfig->toArray();
$arrSettings['params']['dbname'] = 'new_value';
$oConfig= new Zend_Config($arrSettings);