
listener 与 subscriber 的不同点在于,前者在定义阶段就指定了由谁来负责处理事件,而后者是在事件中去决定需要去捕获哪些事件(也就是 EventSubscriberInterface::getSubscribedEvents 方法),后者更灵活, Symfony 内部代码都是使用的 subscriber !
The Listener is signed up specifying the events on which it listens. The Subscriber has a method telling the dispatcher what events it is listening to
This might not seem like a big difference, but if you think about it, there are some cases when you want to use one over the other:
You can assign one listener to many dispatchers with different events, as they are set at registration time. You only need to make sure every method is in place in the listener You can change the events a subscriber is registered for at runtime and even after registering the subscriber by changing the return value of getSubscribedEvents (Think about a time where you listen to a very noisy event and you only want to execute something one time)
The difference between an event listener and an event subscriber is that an event subscriber is a collection of event listeners. At first glance this may seem silly, however consider the following two scenarios:
Scenario 1: One may have a task that has to be actioned upon the occurrence of various events. Here an event listener would be most optimal as this would allow the code of this action to be re-used across the application’s various events and therefore avoid the violation of the fundamental DRY rule.
Scenario 2: One requires a series of specific tasks to be carried out on the occurrence of a specific event. Here, an event subscriber would likely be more suitable.




近期评论