Search code examples
phpzend-framework2zend-controller-plugin

How to access controller plugins in module.php without using any controller object in ZF2..?


I want to add error handling in module.php to add all error messages in flash messenger and redirect to an specific page (in my requirement) :

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

But in some errors its throwing call to undefined method plugin on $e->getTarget() because in some cases error are generating before plugin bindings. I want a way to access redirect and flash messenger plugins without referring any controller.


Solution

  • After trying many ways defined on google i found below way working :

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

    I have posted these solution here so that it can save others time in searching again the same.