Gabor Varga
Gabor Varga

Reputation: 95

Zend Framework 2 dispatch event doesn't run before action


I need some help. I want to run a method in Zend Framework 2 before the controller's action runs. I putted my method in Module.php's onBootstrap, but it doesn't run before action initated.

In Module.php:

public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);

    $app  = $e->getApplication();
    $em = $app->getEventManager();

    $em->attach(MvcEvent::EVENT_DISPATCH, function($e) {
        $controller = $e->getTarget();
        $controller->Init();
    });
}

I want to run the Init() method to my Adapter would be initialized before action runs but it didn't work and I always get this message:
Catchable fatal error: Argument 1 passed to Application\Model\Members::__construct() must be an instance of Zend\Db\Adapter\Adapter, null given, called in PATH\module\Application\src\Application\Controller\AdminController.php on line 39 and defined in PATH\module\Application\src\Application\Model\Members.php on line 17

The members class is in the action which should run and its __construct need to have a valid Adapter object that should be initialized in Init() method.

Could anyone help me? Thanks a lot!

Upvotes: 1

Views: 4150

Answers (2)

philburnett
philburnett

Reputation: 59

You need to set the priority > 1 when attaching to the event.

eg.

$em->attach(MvcEvent::EVENT_DISPATCH, function($e) {
        $controller = $e->getTarget();
        $controller->Init();
    }, 100);

This ensures the code is executed pre-dispatch.

Upvotes: 4

STLMikey
STLMikey

Reputation: 1210

Try a different approach:

I'm assuming your controller extends the Zend\Mvc\Controller\AbstractActionController. Override the parent's onDispatch method in your controller, to do what you need to do:

ex:

class YourController extends AbstractActionController {

    public function onDispatch($event){
        $this->Init();
        return parent::onDispatch($event);
    }
    //your other actions/init methods etc...

}

Upvotes: 6

Related Questions