在我的处理程序方法中,有没有办法确定哪些订阅事件触发了处理程序?
Is there a way, within my handler method, to determine which of the subscribed events triggered the handler?
假设我有一个标记有多个命名事件的 EventListener,或者一个订阅了多个事件的 EventSubscriber,我如何在我的处理程序方法中确定哪些订阅的事件触发了处理程序?
在 sylius 中,所有资源事件都使用通用事件(的后代)class。
我可以看到事件名称未包含在事件 class 中,那么我如何确定哪个订阅事件导致处理程序 运行?
public static function getSubscribedEvents()
{
return [
'sylius.order.post_complete' => 'dispatchMessage',
'sylius.customer.post_register' => 'dispatchMessage',
];
}
更新:我知道在这种情况下我可以调用 get_class($event->getSubject())
并且至少知道我正在处理哪个资源,但是我正在寻找一个更通用的解决方案,可以在任何 symfony 项目中使用.
传递给回调的参数不仅仅是事件对象(您可能会通过在回调 (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'
}
假设我有一个标记有多个命名事件的 EventListener,或者一个订阅了多个事件的 EventSubscriber,我如何在我的处理程序方法中确定哪些订阅的事件触发了处理程序?
在 sylius 中,所有资源事件都使用通用事件(的后代)class。
我可以看到事件名称未包含在事件 class 中,那么我如何确定哪个订阅事件导致处理程序 运行?
public static function getSubscribedEvents()
{
return [
'sylius.order.post_complete' => 'dispatchMessage',
'sylius.customer.post_register' => 'dispatchMessage',
];
}
更新:我知道在这种情况下我可以调用 get_class($event->getSubject())
并且至少知道我正在处理哪个资源,但是我正在寻找一个更通用的解决方案,可以在任何 symfony 项目中使用.
传递给回调的参数不仅仅是事件对象(您可能会通过在回调 (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'
}