Overview
An article that didn't make it in time for the PHP Design Patterns Advent Calendar 2018.
What is the Mediator Pattern?
It means mediator or arbitrator.
A behavioral design pattern that coordinates interactions between objects.
It might be useful when interactions between objects become complex and relationships become difficult to see.
Implementation
<?php
// Mediator
class Receptionist
{
public function checkIn(User $user, $message) // Holds the object to which you want to delegate behavior operations
{
echo $message . ' ' . $user->getName();
}
}
class User
{
private $name;
private $receptionist;
public function __construct($name, Receptionist $receptionist) // Holds the Mediator
{
$this->name = $name;
$this->receptionist = $receptionist;
}
public function getName()
{
return $this->name;
}
public function checkIn($message)
{
$this->receptionist->checkIn($this, $message); // $this!!
}
}
$receptionist = new Receptionist();
$john = new User('John', $receptionist);
$bob = new User('Bob', $receptionist);
$john->checkIn('Welcome!'); // Welcome! John
$bob->checkIn('Hi!'); // Hi! Bob
Thoughts
A pattern to remember when you want to collectively manage the behavior of objects when interactions between classes seem to become complex.