BehavioralPHPverifiedVerified

Mediator Pattern in PHP

Defines an object that encapsulates how a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.

How to Implement the Mediator Pattern in PHP

1Step 1: Define the mediator interface

interface Mediator
{
    public function notify(Component $sender, string $event): void;
}

2Step 2: Define the base component that knows its mediator

abstract class Component
{
    protected ?Mediator $mediator = null;

    public function setMediator(Mediator $mediator): void
    {
        $this->mediator = $mediator;
    }
}

3Step 3: Implement concrete components

class Button extends Component
{
    public function click(): void
    {
        echo "Button clicked\n";
        $this->mediator?->notify($this, 'click');
    }
}

class TextBox extends Component
{
    private string $text = '';

    public function setText(string $text): void
    {
        $this->text = $text;
        $this->mediator?->notify($this, 'textChanged');
    }

    public function getText(): string { return $this->text; }
}

class Label extends Component
{
    public function display(string $text): void
    {
        echo "Label: {$text}\n";
    }
}

4Step 4: Implement the concrete mediator that coordinates components

class FormMediator implements Mediator
{
    public function __construct(
        private readonly Button $submitButton,
        private readonly TextBox $input,
        private readonly Label $status,
    ) {
        $submitButton->setMediator($this);
        $input->setMediator($this);
        $status->setMediator($this);
    }

    public function notify(Component $sender, string $event): void
    {
        match (true) {
            $sender === $this->submitButton && $event === 'click'
                => $this->status->display("Submitted: {$this->input->getText()}"),
            $sender === $this->input && $event === 'textChanged'
                => $this->status->display("Typing: {$this->input->getText()}"),
            default => null,
        };
    }
}

Mediator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Mediator Pattern in the Real World

An air traffic control tower is the classic example. Instead of every plane communicating directly with every other plane—a chaotic and dangerous mess—all aircraft talk only to the control tower. The tower mediates all interactions, directing each plane based on the overall picture it maintains. Planes are decoupled from each other entirely.