如何在不使用ZF2中的任何控制器对象的情况下访问module.php中的控制器插件?

时间:2016-06-14 06:17:04

标签: php zend-framework2 zend-controller-plugin

我想在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()上调用未定义的方法插件,因为在某些情况下,错误是在插件绑定之前生成的。我希望能够在不引用任何控制器的情况下访问redirect and flash messenger plugins

1 个答案:

答案 0 :(得分:4)

尝试了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'));
    }

我在这里发布了这些解决方案,这样可以节省其他人再次搜索的时间。