ZF2:如何为dispatch.error附加模块特定的侦听器 [英] ZF2: How to attach module specific listener for dispatch.error

查看:114
本文介绍了ZF2:如何为dispatch.error附加模块特定的侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以在Zend Framework 2中为事件 dispatch.error 添加一个事件侦听器,该侦听器只会附加到与Module.php?

Is there a way I can attach an event listener for the event dispatch.error in Zend Framework 2, where that listener will only be attached to an EventManager related to the Module.php?

我已经通过将 dispatch 的侦听器附加到全局SharedManager并传递当前模块.php的命名空间作为第一个参数。它工作很好,但不工作,当我尝试相同的 dispatch.error

I have achieved this by attaching listener for dispatch to the global SharedManager and passing the current Module.php's namespace as first param. It works beautifully, but does NOT work, when I try the same for dispatch.error.

这里是一个例子在Module.php中:

Here's an example in Module.php:

public function init(ModuleManager $moduleManager)
{
    $sharedManager  = $moduleManager->getEventManager()->getSharedManager();
    $sharedManager->attach(__NAMESPACE__, 'dispatch', function($e) {
        exit('IT WORKS');
    });
    $sharedManager->attach(__NAMESPACE__, 'dispatch.error', function($e) {
        exit('IT DOES NOT WORK');
    });
}


推荐答案

dispatch但不是dispatch.error是调度事件从控制器内部触发(请参阅Zend\Mvc\Controller\AbstractController :: dispatch)

The reason it is working for dispatch but not dispatch.error is that the dispatch event gets triggered from within in the controller (see Zend\Mvc\Controller\AbstractController::dispatch)

因为您可以使用自己的命名空间控制器来扩展此类,可以将事件与该命名空间相关联。

Because you extend this class with your own namespaced controller, it is possible to associate the event with that namespace.

但是,dispatch.error事件可能会在控制器并且它的命名空间的上下文)被加载。这是根据Zend\Mvc\DispatchListener中的多个条件发生的。

However, the dispatch.error event may be triggered before a controller (and with it the context of your namespace) is ever loaded. This happens according to more than one condition in Zend\Mvc\DispatchListener.

为了自定义dispatch.error的处理方式,你可能需要写一个用于该事件的定制监听器,甚至编写自己的DispatchListener(尽管我建议反对)。然后,您可以看一下routeMatch,找出接下来要做的事情。如果您使用ModuleRouteListener,这可能很简单。

In order to customize the way dispatch.error is handled, you will likely need to write a custom listener for that event, or even write your own DispatchListener (though I'd recommend against that). You can then perhaps look at the routeMatch to figure out what you'd like to do next. If you're using the ModuleRouteListener this could be pretty easy.

这篇关于ZF2:如何为dispatch.error附加模块特定的侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆