在我的Zend Framework 1项目中,我正在尝试向Bootstrap添加一个init.php它将加载一些配置值,然后在配置值不存在时捕获异常。在它捕获异常后,我希望它路由到错误控制器并显示它捕获的异常中的错误消息。
有没有办法在 Bootstrap.php 在 Zend Framework 1 项目中抛出异常,并让错误处理程序像从控制器中抛出异常一样处理它?
更新:感谢David Weinraub,我想出了以下解决方案。
引导.php:
protected function _initRegistry()
{
$options = $this->getOptions();
$fc = Zend_Controller_Front::getInstance();
$fc->registerPlugin(new Application_Plugin_RegistryHandler($options));
}
注册表处理程序.php:
use Application'Service'Config'Config;
use Application'Service'Config'MailConfig;
/**
* Handles the loading of objects and values into the registry, we use a plugin
* so exceptions can be thrown and caught with
* Zend_Controller_Plugin_ErrorHandler.
*/
class Application_Plugin_RegistryHandler extends Zend_Controller_Plugin_Abstract
{
/**
* @var array
*/
private $options;
/**
* @param array $options
*/
public function __construct($options)
{
$this->options = $options;
}
/**
* Load the config classes into registry on route startup
* so the error controller should be loaded and ready to catch exceptions.
*
* @param Zend_Controller_Request_Abstract $request
*/
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$registry = Zend_Registry::getInstance();
$mailConfig = new MailConfig($this->options);
$config = new Config($this->options);
$config->setMailConfig($mailConfig);
$registry->set('config', $config);
}
}
从这里抛出的任何异常都会被错误处理程序捕获和处理,并且可以显示一条很好的消息,例如"本地缺少配置值'doctrine.conn.database'.ini",然后我使用注册表从应用程序中的任何位置访问这些配置值(实体管理器和稍后添加的邮件处理程序)。
我希望我有权将这个项目移动到 Zend Framework 2,更容易使用。
在引导过程中使用 ErrorController
处理异常通常是有问题的。毕竟,ErrorController
本身取决于这种引导。
如果可能的话,您可以将配置检查放在以 routeStartup
运行的前端控制器插件中吗?到那时,引导已经发生,标准ErrorHandler
插件已经注册,因此在那里抛出异常应该会导致ErrorController
处理它。
我想您可以尝试/捕获检查配置的块。然后,在 catch 中,您检查错误处理程序插件是否已注册。如果没有,则自行手动注册,然后重新引发异常。没有测试,只是大声思考。