phpzend-framework2zend-framework-mvc

ZF2 - Trigger MvcEvent::EVENT_DISPATCH_ERROR from View Controller


I am using a Restful Controller and on certain conditions, I would like the trigger the MvcEvent::EVENT_DISPATCH_ERROR and stop execution of the controller immediately after. In my Module class, I have attached an event listener for this but I can't find a way to trigger it from the view controller.

My Module code is:

public function onBootstrap(MvcEvent $mvcEvent) {
    $eventManager = $mvcEvent->getApplication()
        ->getEventManager();

    $eventManager->attach(array(MvcEvent::EVENT_DISPATCH_ERROR, MvcEvent::EVENT_RENDER_ERROR), array($this, 'error'));
}

public function error(MvcEvent $mvcEvent) {
    echo $mvcEvent->getError();
    die();
}

and my Controller code is:

public function indexAction() {
    $mvcEvent = $this->getEvent();

    $mvcEvent->setError('test-error-code');
    $mvcEvent->getTarget()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $mvcEvent);
    return;
}

Solution

  • I think the problem is that you're not attaching to the Application's sharedEventManager. You can also use the Controller's own Event Manager to trigger the event.

    Try something like this:

    Module.php

    public function onBootstrap(MvcEvent $mvcEvent) {
    
        $eventManager = $mvcEvent->getApplication()->getEventManager()->getSharedManager();
    
        $eventManager->attach('Zend\Stdlib\DispatchableInterface', MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'error'));
    }
    

    Controller

    public function indexAction() {
    
        $mvcEvent = $this->getEvent();
        $mvcEvent->setError('test-error-code');
    
        $this->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $mvcEvent);
    
        return;
    }