ZF2将侦听器与EventManager分离 [英] ZF2 detach listener from EventManager
问题描述
实施一个新的ZF2应用程序时,我发现自己在EventManager中挣扎.在应用程序模块中,我创建了AuthenticationListener
和NotifierListener
.第一个检查对用户的身份验证是否正确,第二个显示针对登录用户的自定义消息.
Implementing a new ZF2 app I found myself struggling with the EventManager. In the application module I created an AuthenticationListener
and a NotifierListener
. The first checks for proper authentication on users and the second displays custom messages addressed to the logged user.
现在,我正在创建一个新模块,该模块调度xml文件以导出.我想保留AuthenticationListener
,但分离NotifierListener
以避免E_NOTIFY
错误.问题是,在阅读博客/源代码/文档(相当糟糕)并拔掉头发之后,我无法理解如何分离上面提到的侦听器.
Now I'm creating a new module that dispatches xml files to export. I want to keep the AuthenticationListener
but detach the NotifierListener
to avoid E_NOTIFY
errors. The problem is that after reading blogs/source code/documentation (pretty poor) and pulling my hair out I'm unable to understand how to detach the listener mentioned above.
public function onBootstrap($e)
{
$eventManager = $e->getApplication()->getEventManager();
$authListener = new AuthenticationListener();
$authListener->attach($eventManager);
$notifyListener = new NotifyListener();
$notifyListener->attach($eventManager);
}
新module.php
public function onBootstrap($e)
{
$eventManager = $e->getApplication()->getEventManager();
// ... $eventmanager->detach('NotifyListener');
}
推荐答案
答案是使您的监听器成为一种服务
The answer is to make your listener a service
由于不需要构造函数参数,因此可以调用,因此请在invokables数组中进行设置
Since it requires no constructor params, it's invokable, so set it in the invokables array
public function getServiceConfig()
{
return array(
'invokables' => array(
'NotifyListener' => 'FQCN\To\NotifyListener',
),
);
}
从服务管理器中获取它,而不是直接在您的引导程序中创建新实例
Fetch it from the service manager instead of creating a new instance directly in your bootstrap
public function onBootstrap($e)
{
$eventManager = $e->getApplication()->getEventManager();
$sm = $e->getApplication()->getServiceManager();
$notifyListener = $sm->get('NotifyListener')
$notifyListener->attach($eventManager);
}
任何要分离它的地方,只需要能够找到ServiceManager
Anywhere you want to detach it, you just need to be able to get at the ServiceManager
// in any ServiceLocator aware class
$sm = $this->getServiceLocator();
$eventManager = $sm->get('Application')->getEventManager();
$notifyListener = $sm->get('NotifyListener');
$notifyListener->detach($eventManager);
这篇关于ZF2将侦听器与EventManager分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!