Zend Framework 2 dispatch event doesn't run be

2019-06-01 03:46发布

问题:


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!

回答1:

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...

}


回答2:

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.