微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何禁用特定模块的错误控制器

我有一个模块Api,我试图实现RESTful API.问题是当我在该模块中抛出异常时,我希望抛出异常而不是由认模块中的错误控制器处理.

是否可以在Zend Framework中仅为特定模块禁用错误控制器?

解决方法:

使用以下方法可以禁用特定模块的错误处理程序.在这个例子中,我将调用你的RESTful模块休息.

首先,在您的应用程序中创建一个插件.例如,这将是Application_Plugin_RestErrorHandler.将以下代码添加到application / plugins / RestErrorHandler.PHP

class Application_Plugin_RestErrorHandler extends Zend_Controller_Plugin_Abstract
{
    public function predispatch(Zend_Controller_Request_Abstract $request)
    {
        $module = $request->getModuleName();

        // don't run this plugin unless we are in the rest module
        if ($module != 'rest') return ;

        // disable the error handler, this has to be done prior to dispatch()
        Zend_Controller_Front::getInstance()->setParam('noErrorHandler', true); 
    }
}

接下来,在您的模块Bootstrap for rest模块中,我们将注册插件.这是在modules / rest / Bootstrap.PHP中.由于所有模块引导都是在当前模块下执行的,因此可以在主引导程序中执行,但我喜欢在该模块的引导程序中注册与特定模块相关的插件.

protected function _initPlugins()
{
    $bootstrap = $this->getApplication();
    $bootstrap->bootstrap('frontcontroller');
    $front = $bootstrap->getResource('frontcontroller');

    // register the plugin
    $front->registerPlugin(new Application_Plugin_RestErrorHandler());
}

另一种可能性是保留错误处理程序,但使用特定于模块的错误处理程序.这样,rest模块的错误处理程序可能会有不同的行为,并输出REST友好错误.

为此,将ErrorController.PHP复制到modules / rest / controllers / ErrorController.PHP并将该类重命名为Rest_ErrorController.接下来,将错误控制器的视图脚本复制到modules / rest / views / scripts / error / error.phtml.

根据自己的喜好自定义error.phtml,以便错误消息使用您的rest模块使用的相同JSON / XML格式.

然后,我们将对上面的插件稍作调整.我们要做的是告诉Zend_Controller_Front使用来自其余模块的ErrorController :: errorAction而不是认模块.如果需要,您甚至可以使用与ErrorController不同的控制器.将插件更改为如下所示:

class Application_Plugin_RestErrorHandler extends Zend_Controller_Plugin_Abstract
{
    public function predispatch(Zend_Controller_Request_Abstract $request)
    {
        $module = $request->getModuleName();

        if ($module != 'rest') return ;

        $errorHandler = Zend_Controller_Front::getInstance()
                        ->getPlugin('Zend_Controller_Plugin_ErrorHandler');

        // change the error handler being used from the one in the default module, to the one in the rest module
        $errorHandler->setErrorHandlerModule($module); 
    }
}

使用上面的方法,您仍然需要在Bootstrap中注册插件.

希望有所帮助.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐