2012-02-16 65 views
4

我想覆盖Zend_Config方法__set($ name,$ value),但我有同样的问题。覆盖Zend_Config并访问父节点

$名字 - 返回重写配置值的当前关键,例如:

$this->config->something->other->more = 'crazy variable'; // $name in __set() will return 'more' 

因为在配置每一个节点是新Zend_Config的()类。

那么 - 如何从覆盖__set()metod获取父节点名称的访问权限?我必须覆盖控制器中的相同配置值,但是要覆盖控制权,并且不允许覆盖其他配置变量,我想在其他配置变量中指定一个树数组,覆盖允许的配置密钥。

回答

3

Zend_Config是只读的,除非您在构建过程中将$ allowModifications设置为true。

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); 

结果

字符串 '测试'(长= 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. 
    } 
} 
+0

我对它了解得非常好,但我不希望允许修改整个变量,但仅用于指定变量。所以我必须重载Zend_Config,并手动过滤哪个变量,我想覆盖,而不是。 – BlueMan 2012-02-17 11:21:26

+0

在这种情况下,看到我的以上 – vascowhite 2012-02-17 12:28:56

+0

啊,我现在看到你的问题。返回的对象始终是一个Zend_Config!我的第二个解决方案不起作用。我会再尝试 :) – vascowhite 2012-02-17 12:40:58

0

总是有另一种方式:)

$arrSettings = $oConfig->toArray(); 
$arrSettings['params']['dbname'] = 'new_value'; 
$oConfig= new Zend_Config($arrSettings);