Search code examples
zend-framework2zend-framework3

ZF3 - EventManager and dispatch event


in an older ZF2 application I change the layout in a dispatch listener, if the matched route starts with admin. Now I started a new project and want to use ZF3 components, but the event manager does have some changes and I get the following exception:

Uncaught TypeError: Argument 2 passed to Zend\EventManager\EventManager::attach() must be callable, none given

I don't know really how to handle this in ZF3. Here are my relevant source codes to change the layout in my ZF2 application:

Module.php

namespace Admin;

use Zend\EventManager\EventInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;

class Module implements BootstrapListenerInterface {

    public function onBootstrap(EventInterface $event) {
        $application = $event->getApplication();
        $eventManager = $application->getEventManager();
        $serviceManager = $application->getServiceManager();

        $eventManager->attach($serviceManager->get('Admin\Listener\Dispatch'));
    }

}

DispatchListener.php

namespace Admin\Listener;

use Zend\EventManager\AbstractListenerAggregate;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\Mvc\MvcEvent;

class DispatchListener extends AbstractListenerAggregate {

    public function attach(EventManagerInterface $eventManager) {
        $this->listeners[] = $eventManager->attach(
            MvcEvent::EVENT_DISPATCH, array($this, 'onDispatch'), 100
        );
    }

    public function onDispatch(EventInterface $event) {
        $matchedRouteName = $event->getRouteMatch()->getMatchedRouteName();

        if (strpos($matchedRouteName, 'admin') === 0) {
            $event->getViewModel()->setTemplate('layout/admin');
        }
    }

}

Solution

  • zf3 is more focused on decoupling components, it seems aggregates has been removed to attach event see the api document

    event manager

    for short the attach message says

    attach($eventName, callable $listener, $priority = 1) : callable
    

    I hope since you are not specifying the eventName you are getting the error message

    update:

    see the link to migration guide from v2 to v3 for event manager

    Removed functions