Zend Framework:如何取消Zend_Registry中的密钥?
-
03-07-2019 - |
题
我正在测试我的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');
更新:我真正想知道的是,我应该如何测试我的方法在“域”时引发异常?配置文件中的密钥未设置。
解决方案
更改配置对象值的唯一真正方法是将其转储到变量,取消设置相关项,请求注册表删除配置密钥,然后重置它。
<?php
$registry = Zend_Registry::getInstance();
$config = $registry->get('config');
unset($config->domain);
$registry->offsetUnset('config');
$registry->set('config', $config);
?>
但是,要使其正常工作,您必须在将Zend_Config对象首次设置到注册表之前将其设置为可编辑。
您应该考虑以这种方式编辑注册表不是最佳做法。特别是,Zend_Config对象在最初实例化后设计为静态。
我希望我能够很好地理解你的问题!
其他提示
如果你的'config'实际上是 Zend_Config
,那么默认情况下它是只读的。
Zend_Config
构造函数的可选第二个参数是boolean $ allowModifications
,默认设置为 false
。
您可能在 bootstrap.php
中使用
Zend_Config_Ini
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)
尝试:
unset($config->domain);
然后使用修改后的 Zend_Config
类重新注册 $ registry-&gt; config
。请注意,正如vartec所说,您必须将 Zend_Config
实例实例化为可编辑:
$config = new Zend_Config('filename', true);
您尝试调用的 __ unset
方法是 unset 时调用的“nofollow noreferrer”>魔术方法。
我发现你正在尝试删除$ config中的值,其中$ config在删除之前存储在Zend_Registry中。因此,如果删除该值不会影响Zend_Registry中存储的$ config值,我假设通过调用Zend_Registry :: get(),您具有$ config的值,而不是Zend_Registry中$ config的引用。因此,当您在复制的$ config中更改某些内容时,它不会影响存储的内容。我建议您首先更改$ config,然后通过再次在Zend_Registry中设置$ config来覆盖注册表中的$ config。
对于那些希望完成标题要求的人来说,取消设置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')