Zend Framework将自定义事件附加到共享事件管理器

时间:2016-12-05 23:33:44

标签: php zend-framework zend-framework-mvc zend-framework3 zf3

使用Zend Framework,我想在我的应用程序/模块上附加一个事件,以便在每个调度事件中为每个模块调用此函数。这是我的代码:

类模块 {     公共函数getConfig()     {         返回包括 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。

不知道我错过了什么。据我所知,我需要使用共享事件管理器对整个应用程序有效。

帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

为此(监听MVC事件)工作,您不需要共享事件管理器,而是MVC事件管理器。像这样更改你的代码,它将按预期工作:。

$application    = $event->getApplication();
$eventManager   = $application->getEventManager();

// Register the event listener method onDispatch
$eventManager->attach(MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100);

另请参阅this great blog post,了解有关何时使用共享事件管理器的更多详细信息。这篇博文中也解释了这个特例:

  

MVC活动的特例
  我之前说过,我们应该使用共享事件管理器。但是有一个特定的情况:我们从onBootstrap方法检索的事件管理器是MVC事件管理器。这意味着此事件管理器知道框架触发的事件。这意味着如果要将侦听器添加到Zend\Mvc\MvcEvent类的事件,则可以在不使用共享事件管理器的情况下执行此操作:

相关问题