使用 Zend Framework,我想在我的应用程序/模块上附加一个事件,以便在每个模块的每个调度事件上调用此函数。这是我的代码:
class Module
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function onBootstrap(MvcEvent $event)
{
$application = $event->getApplication();
$serviceManager = $application->getServiceManager();
$sessionManager = $serviceManager->get(SessionManager::class);
// Get event manager.
$eventManager = $event->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
// Register the event listener method onDispatch
$sharedEventManager->attach(AbstractActionController::class,
MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100);
}
public function onDispatch(MvcEvent $event)
{
// Will perform application wide ACL control based on controller,
// action and user data.
}
}
由于某种原因,即使应用程序屏幕已加载,我的 onDispatch 也从未被调用。
不知道我错过了什么。据我所知,我需要使用共享事件管理器才能对整个应用程序有效。
为此(监听 MVC 事件)工作,您不需要共享事件管理器,而是 MVC 事件管理器。像这样更改您的代码,它将按预期工作:.
$application = $event->getApplication();
$eventManager = $application->getEventManager();
// Register the event listener method onDispatch
$eventManager->attach(MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100);
另请阅读这篇精彩的博客文章,了解有关何时使用共享事件管理器的更多详细信息。此博文中也解释了这种特殊情况:
MVC 事件的特例
我之前说过我们应该使用共享事件管理器。但有一种特定情况:我们从方法检索的事件管理器是 MVC 事件管理器。这意味着该事件管理器知道框架触发的事件。这意味着,如果您想向onBootstrap
类的事件添加侦听器,无需使用共享事件管理器即可完成:Zend\Mvc\MvcEvent