ZF1从bootstrap调度错误控制器

时间:2013-11-14 04:27:17

标签: php zend-framework

在我的Zend Framework 1项目中,我尝试向Bootstrap.php添加一个init,它将加载一些配置值,然后在配置值不存在时捕获异常。在它捕获异常后,我希望它路由到错误控制器并显示它捕获的异常中的错误消息。

有没有办法在Zend Framework 1项目的Bootstrap.php中抛出异常并让错误处理程序处理它,就像从控制器中抛出异常一样?

更新 感谢 David Weinraub ,我提出了以下解决方案。

bootstrap.php中:

protected function _initRegistry()
{
    $options = $this->getOptions();
    $fc = Zend_Controller_Front::getInstance();
    $fc->registerPlugin(new Application_Plugin_RegistryHandler($options));
}

RegistryHandler.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);
    }
}

从此处抛出的任何异常都会被错误处理程序捕获并处理,并且可以显示一条很好的消息,例如local.ini中缺少“配置值'doctrine.conn.database'”,然后我使用注册表来访问这些配置从应用程序的任何位置开始的值(实体管理器和稍后要添加的邮件处理程序)。

我希望我有权将此项目移至Zend Framework 2,更容易使用。

1 个答案:

答案 0 :(得分:2)

使用ErrorController在bootstrap 期间处理异常通常会有问题。毕竟,ErorController本身取决于引导。

如果可能,您可以将配置检查置于routeStartup ErrorHandler运行吗?到那时,引导已经发生并且标准ErrorController插件已经注册,因此抛出异常会导致{{1}}处理它。

我想你可以尝试/捕获你检查配置的块。然后,在catch中,检查ErrorHandler插件是否已经注册。如果没有,那么您自己手动注册,然后重新抛出异常。没有经过测试,只是大声思考。