Reputation: 85368
FYI I'm just getting started with Symfony, with that said...
What advantage would there be using a Listener as a Service instead of a Service?
Looking over the docs I see I can use a Listener as a Service:
But I could also use the Event Dispatcher:
to get the same functionality or am I missing something?
What I'm looking to do is create a service that listens for custom events and I'm a little confused on the route I should take with the above scenario. I have seen some posts about each setup but nothing comparing the two and the differences.
Thanks for any insight
Upvotes: 1
Views: 335
Reputation: 10356
In a nutshell, events in a Symfony application are similar to events in JavaScript: instead of listening to mostly UI related events (such as mouse clicks, hovers etc) you're listening to arbitrary events in the application (such as exceptions getting throws, response being sent, user being created etc).
EventDispatcher is built around the observer pattern. For any occurring events the dispatcher notifies all the registered listeners about the event. Surely you could retrieve the dispatcher from the service container and register the listener by hand, but this doesn't allow us to listen to events being fired beforehand. Even worse, the listener is only registered in that controller action.
By configuring the listener to be a service, you're essentially letting the framework do the registering process itself. If you have a look at app/cache/dev/appDevDebugContainer.php
(can be a bit different name, writing this off top of my head) and search for event_dispatcher
, you should be able to see how the events have been automatically registered.
Upvotes: 2
Reputation: 11351
As the name suggests, an even listener "listens" to events, while an event dispatcher "dispatchs" (sends) them.
If you want a service that listen to custom events (i.e. events that you create), then you would have to create both an event dispatcher to send the events and an even listener to listen for them
Upvotes: 0