如何在不使用ZF2 ..中任何控制器对象的情况下访问module.php中的控制器插件?
作者:互联网
我想在module.php中添加错误处理,以在Flash Messenger中添加所有错误消息并重定向到特定页面(根据我的要求):
public function handleError(MvcEvent $e) {
$exception = $e->getParam('exception');
$controller = $e->getTarget();
//echo $exception->getMessage(); exit;
if (!$e->getApplication()->getServiceManager()->get('AuthService')->hasIdentity()) {
$controller->flashMessenger()->addErrorMessage("Session Expired..!!");
return $e->getTarget()->plugin('redirect')->toRoute('auth', array('action' => 'login'));
}
switch ($exception->getCode()) {
case "2003" :
$controller->flashMessenger()->addErrorMessage("Unable to connect database..!!");
break;
default :
$controller->flashMessenger()->addErrorMessage($exception->getMessage());
break;
}
$e->getApplication()->getServiceManager()->get('AuthService')->clearIdentity();
return $e->getTarget()->plugin('redirect')->toRoute('auth', array('action' => 'login'));
}
但是在某些错误中,它会抛出对$e-> getTarget()上未定义方法插件的调用,因为在某些情况下,错误是在插件绑定之前生成的.我想要一种无需引用任何控制器即可访问重定向和Flash Messenger插件的方法.
解决方法:
在尝试了多种在google上定义的方法后,我发现以下工作方式:
public function handleError(MvcEvent $e) {
$exception = $e->getParam('exception');
$sm = $e->getApplication()->getServiceManager();
$flashmessenger = $sm->get('ControllerPluginManager')->get('flashmessenger');
//echo $exception->getMessage(); exit;
if (!$e->getApplication()->getServiceManager()->get('AuthService')->hasIdentity()) {
$flashmessenger->addErrorMessage("Session Expired..!!");
return $sm->get('ControllerPluginManager')->get('redirect')->toRoute('auth', array('action' => 'login'));
}
switch ($exception->getCode()) {
case "2003" :
$flashmessenger->addErrorMessage("Unable to connect database..!!");
break;
default :
$flashmessenger->addErrorMessage($exception->getMessage());
break;
}
$e->getApplication()->getServiceManager()->get('AuthService')->clearIdentity();
return $sm->get('ControllerPluginManager')->get('redirect')->toRoute('auth', array('action' => 'login'));
}
我在这里发布了这些解决方案,这样可以节省其他人再次搜索的时间.
标签:zend-framework2,php,zend-controller-plugin 来源: https://codeday.me/bug/20191026/1940581.html