我正在测试我的Zend Framework应用程序,并希望测试在注册表中未设置特定键时发生的事情。这是我正在测试的功能:
protected function getDomainFromConfig() {
$config = Zend_Registry::get('config');
if (!isset($config->domain)) {
throw new Exception('Please make sure you have "domain" set in your config file and your config file is being set in the Zend_Registry.');
}
return $config->domain;
}
如何取消注册表中的密钥?我试过这个,但它不起作用:
$config = Zend_Registry::get('config');
$config->__unset('domain');
更新:我真正想知道的是,如果未设置配置文件中的“domain”键,我应该如何测试我的方法是否会引发异常。
答案 0 :(得分:7)
更改配置对象值的唯一真正方法是将其转储到变量,取消设置相关项,请求注册表删除配置密钥,然后重置它。
<?php
$registry = Zend_Registry::getInstance();
$config = $registry->get('config');
unset($config->domain);
$registry->offsetUnset('config');
$registry->set('config', $config);
?>
但是,要使其正常工作,您必须在将Zend_Config对象首次设置到注册表之前将其设置为可编辑。
您应该考虑以这种方式编辑注册表不是最佳做法。特别是,Zend_Config对象在最初实例化后设计为静态。
我希望我能够很好地理解你的问题!
答案 1 :(得分:1)
如果您的'config'实际上是Zend_Config
,那么默认情况下它是只读的。
Zend_Config
构造函数的可选第二个参数是布尔$allowModifications
,默认设置为false
。
您可能使用
在Zend_Config_Ini
中创建bootstrap.php
new Zend_Config_Ini(APPLICATION_PATH . '/config/app.ini',
APPLICATION_ENVIRONMENT)
追加$allowModifications
param:
new Zend_Config_Ini(APPLICATION_PATH . '/config/app.ini',
APPLICATION_ENVIRONMENT,
true)
答案 2 :(得分:0)
尝试:
unset($config->domain);
然后使用修改后的$registry->config
类重新注册Zend_Config
。请注意,正如vartec所说,您必须将Zend_Config
实例实例化为可编辑的:
$config = new Zend_Config('filename', true);
您尝试调用的__unset
方法是magic method,在您对实例使用unset
时会调用该方法。
答案 3 :(得分:0)
我发现你正在尝试删除$ config中的值,其中$ config在删除之前存储在Zend_Registry中。因此,如果删除该值不会影响Zend_Registry中存储的$ config值,我假设通过调用Zend_Registry :: get(),您具有$ config的值,而不是Zend_Registry中$ config的引用。因此,当您在复制的$ config中更改某些内容时,它不会影响存储的内容。我建议您首先更改$ config,然后通过再次在Zend_Registry中设置$ config来覆盖注册表中的$ config。
答案 4 :(得分:0)
对于那些希望完成标题要求的人来说,取消设置Zend_Registry键:
class My_Registry extends Zend_Registry
{
/**
*
* @param type $index
*/
public static function delete($index)
{
$instance = self::getInstance();
if ($instance->offsetExists($index)) {
$instance->offsetUnset($index);
}
}
}
致电:My_Registry::delete('key')