On init you'll need to get the shared event manager from the module manager:
<?php
use Laminas\ModuleManager\Feature\InitProviderInterface;
use Laminas\ModuleManager\ModuleManagerInterface;
use Laminas\Mvc\Application;
use Laminas\Mvc\MvcEvent;
final class Module implements InitProviderInterface
{
public function init(ModuleManagerInterface $manager): void
{
$sharedEventManager = $manager->getEventManager()->getSharedManager();
$sharedEventManager->attach(
Application::class,
MvcEvent::EVENT_DISPATCH,
function () {
var_Dump('dispatch from init');
}
);
}
}
The SharedEventManager
is usually (or should be) shared between all event manager instances. This makes it possible to call or create events from other event manager instances. To differentiate between event names an identifier is used (so you can have more then one event with the same name). All MvcEvents belong to the Laminas\Mvc\Application
identifier. Laminas\ModuleManager\ModuleManager
has it's own EventManager instance, that is why you'll need to add the event to the SharedEventManager (init()
is called by the ModuleManager and Laminas\ModuleManager\ModuleEvent
is used).
onBootstrap()
will be called by Laminas\Mvc\Application
, that why you get the correct EventManager instance there.
As @Dimitry suggested: you should add that event in onBootstrap()
as the dispatching process is part of the application and not the module manager. In init()
you should only add bootstrap events.
And btw: you should use the Laminas\ModuleManager\Feature\*
interfaces to make your application a bit more robust to future updates.