Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Zend Framework 2, how do you use a controller plugin outside the controller

Specifically, I'm trying to use the FlashMessenger plugin form within my Module.php file.

Right now the method inside my Application/Module.php file looks like this:

public function checkAcl(MvcEvent $e) {
    // code to determine route and role ...

    if (!$e->getViewModel()->acl->isAllowed($userRole, $route)) {
        $flashMessenger = $e->getController()->plugin('flashMessenger');
        $flashMessenger->addMessage('You must be logged in');

        // code to redirect to login page ...
    }
}

But that is not working because $e->getController() is returning a string, not the controller object. Any help accessing either the controller or the plugin directly is appreciated.

like image 971
Chris O'Connell Avatar asked May 14 '13 23:05

Chris O'Connell


1 Answers

You can use the ControllerPluginManager to get an instance of the flashMessenger from any event handler in your Module.php like so:

public function myEventHandler(MvcEvent $e) {
    $sm = $e->getApplication()->getServiceManager();
    $flash = $sm->get('ControllerPluginManager')->get('flashMessenger');
    $flash->addErrorMessage('test');
    // ...
}

Obviously you can do this for any controller plugin.

like image 67
Ezequiel Muns Avatar answered Dec 28 '22 10:12

Ezequiel Muns