Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern in Symfony2: is EventDispatcher a Mediator or Event Aggregator?

From Symfony2's EventDispatcher component documentation:

The Symfony2 EventDispatcher component implements the Mediator pattern in a simple and effective way to make all these things possible and to make your projects truly extensible.

I have been reading about Event Aggregator and Mediator patterns and their differences. To me it looks like Event Aggregator is a specific case of Mediator, which uses events to facilitate communication, and has no business logic whatsoever inside. Mediator on the other hand is more generic, and can allow some business logic to decide if certain communication should go through.

So I checked the source code of Symfony2's EventDispatcher or TraceableEventDispatcher, and found that the only logic that may alter communication is checking if event propagation has been stopped, as follows:

protected function doDispatch($listeners, $eventName, Event $event)
{
    foreach ($listeners as $listener) {
        call_user_func($listener, $event, $eventName, $this);
        if ($event->isPropagationStopped()) {
            break;
        }
    }
}

Is this why EventDispatcher in Symfony2 implements Mediator pattern but not Event Aggregator pattern? If the logic to check for isPropagationStopped is moved out of EventDispatcher (say, to the event listeners), then this would implements Event Aggregator?

like image 776
hidro Avatar asked Oct 21 '22 15:10

hidro


1 Answers

Event Aggregator is similar to Observer pattern, the Subject just notifies to Observer objects that there's a change, those need to update no matter what kind of event it is.

Symfony2's EventDispatcher implements Mediator pattern because it acts like a router, decides what event will be triggered by the listener which can subscribe to more than one event. As you can see, even removing isPropagationStopped part, EventDispatcher still needs the event name to determine which event to fire.

Anthony Ferrara has a great blog post discussing about this matter

like image 107
Pupi Avatar answered Oct 23 '22 04:10

Pupi