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中注册插件. 希望有所帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |