_Let's talk about_ # The Mediator Pattern --- ## Intent ### Defines an object that encapsulates how a set of objects interact Mediator **promotes loose coupling** by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. --- ![Mediator UML](https://www.baeldung.com/wp-content/uploads/2019/03/mediator.png) ## Use When - Communication between sets of objects is well defined and complex. - Too many relationships exist and common point of control or communication is needed. --- - An instance implementing `Mediator` is shared between multiple instances that implement a `Colleague` interface. - When events occur in each of the `Colleague` instances, the mediator is triggered, which in turn reacts to the event. https://refactoring.guru/design-patterns/mediator/php/example#example-0 --- ## Do *we* use this? - AFAIK, we don't. Not by the textbook anyway. - Events of each `Colleague` object influence the other objects. Therefore there has to be more than one of them. - [ExceptionHandler](https://gitlab.mfb.io/deathstar/IMS/blob/master/lib/projectionist/src/ExceptionHandler.php) !== Mediator (== Facade) - [EventRecorder](https://gitlab.mfb.io/deathstar/php-internal-open-source-libraries/ds-messaging-common/blob/master/src/EventRecorder.php) !== Mediator (== Observer) --- ## Would this be useful to us? If we have multiple sibling objects that interact with each other. ### Repositories? --- ```php $this->sessionRepository->update($session); //SessionRepository() function update(Session $session) { $sessionMediator->sessionWasUpdated($session); // Do SQL query to save the session... } //TraceRepository() function updateTraceForSession(Session $session); //SessionMediator($sessionRepository, $traceRepository) function sessionWasUpdated(Session $session) { $traceRepository->updateTraceForSession($session); } ``` ### Useful :question:
{"metaMigratedAt":"2023-06-14T22:35:18.818Z","metaMigratedFrom":"YAML","title":"Mediator Pattern","breaks":true,"slideOptions":"{\"transition\":\"fade\"}","contributors":"[{\"id\":\"04c4d2ca-5f8e-4a20-9132-7b053dd72497\",\"add\":3955,\"del\":1902}]"}
    307 views