Event dispatcher
Event dispatcher
Events and Event Listeners
Creating an event listener
Using php attributes
Creating an Event Subscriber
Event Subscriber: Class that defines one or more methods that listen to on or various events. Self-contained, doesn’t need yaml config
Dispatch custom event
Event
Subscriber
Observer Pattern:
Purpose: The Observer pattern is a software design pattern where an object (known as the subject) maintains a list of its dependents (observers) and notifies them automatically of any state changes, usually by calling one of their methods.
In Symfony: In the context of Symfony's EventDispatcher, the events are the "subjects," and the event listeners or subscribers are the "observers". When an event is dispatched, the EventDispatcher notifies all registered listeners for that event, thus "observing" the event.
Benefits: This pattern promotes loose coupling, as the subject doesn't need to know anything about the observers beyond the fact that they implement a certain interface. This allows for very dynamic behavior, as observers can be added, removed, or changed at runtime.
Mediator Pattern:
Purpose: The Mediator pattern is used to reduce chaos among interconnected components in a system by encapsulating the way these components interact. It promotes the principle that "objects don't call each other directly but instead go through a mediator."
In Symfony: The
EventDispatcher
acts as a mediator in the sense that it's the object through which events (messages) pass. The components dispatching events and the listeners responding to them don't interact directly. They connect through the dispatcher, which handles the routing of events to the appropriate listeners.Benefits: This central point of control allows for more controlled, maintainable interactions between objects. It also makes your system easier to understand, change, and extend.