【问题标题】:Is there a way, within my handler method, to determine which of the subscribed events triggered the handler?有没有办法在我的处理程序方法中确定哪些订阅的事件触发了处理程序?
【发布时间】:2019-09-18 14:33:08
【问题描述】:

假设我有一个标记有多个命名事件的 EventListener,或者一个订阅多个事件的 EventSubscriber,我如何在我的处理程序方法中确定哪些订阅的事件触发了处理程序?

在 sylius 中,所有资源事件都使用 Generic Event 类(的后代)。

我可以看到事件名称不包含在事件类中,那么我如何确定哪些订阅的事件导致处理程序运行?

    public static function getSubscribedEvents()
    {
        return [
            'sylius.order.post_complete' => 'dispatchMessage',
            'sylius.customer.post_register' => 'dispatchMessage',
        ];
    }

更新:我知道在这种情况下我可以调用 get_class($event->getSubject()) 并且至少知道我正在处理哪个资源,但是我正在寻找一个更通用的解决方案,可以在任何 symfony 项目中工作。

【问题讨论】:

  • 你可以使用 Symfony Profiler 并打开 Events 选项卡
  • @Dr.X 这可能有助于调试,但不是我可以在我的代码中“在我的处理程序方法内”使用的东西来决定采取哪些操作。

标签: symfony events sylius sylius-resource


【解决方案1】:

传递给回调的参数不仅仅是事件对象(您可能会通过在回调 (dispatchMessage) 中调用 func_get_args() 比在文档中更快地遇到它们 :-))。它们不是强制性的,但它们包含您可能需要的内容。

回调被调用,作为参数:
- 事件(对象)
- 活动名称(您要查找的内容
- 调度程序实例

(见https://github.com/symfony/event-dispatcher/blob/master/EventDispatcher.php#L231

因此,在您的情况下,您可以使用以下内容:

public static function getSubscribedEvents()
{
    return [
        'sylius.order.post_complete' => 'dispatchMessage',
        'sylius.customer.post_register' => 'dispatchMessage',
    ];
}

public function dispatchMessage(GenericEvent $event, string $eventName, EventDispatcherInterface $eventListener)
{
    // Here, $eventName will be 'sylius.order.post_complete' or 'sylius.customer.post_register'
}

【讨论】:

  • 不需要使用 func_get_args。 dispatchMessage($event,$eventName) 可以解决问题。
  • 查看“不那么明显”的其他参数只是一个调试技巧,而不是应该使用的实际代码:-),来澄清我的答案。
  • 感谢伊万西斯!这正是我一直在寻找的......我没想到第一个答案会如此重要!
  • @Cerad 如果您可以充实您的评论以形成完整的答案,我会将其作为接受的答案,因为它最接近我实际要求的...谢谢:)
  • 让我们看看@evanesis 是否回来并调整他们的答案。他们已经完成了 99% 的工作。事实上,正是他们的回答让我想起了 $eventName 作为第二个参数传递。
猜你喜欢
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 1970-01-01
  • 2018-01-26
  • 2015-09-21
  • 2013-01-04
  • 2016-09-06
  • 1970-01-01
相关资源
最近更新 更多