iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Mediator

The Mediator pattern centralises communication between a group of objects so they do not refer to each other directly. Instead of N components knowing about N-1 others, each only knows the mediator. This trades a star topology for a hub-and-spoke and is the right call when the coupling between components has become the dominant source of change.

A chat-room mediator coordinating users

EXAMPLE
<?php
// Mediator interface
interface ChatMediator {
    public function send(string $from, string $message, ?string $to = null): void;
    public function register(User $user): void;
}

// Concrete mediator: knows every participant, routes messages
class ChatRoom implements ChatMediator {
    /** @var array<string, User> */
    private array $users = [];

    public function register(User $user): void {
        $this->users[$user->name()] = $user;
        $user->setRoom($this);
    }

    public function send(string $from, string $message, ?string $to = null): void {
        if ($to !== null) {
            if (isset($this->users[$to])) $this->users[$to]->receive($from, $message);
            return;
        }
        foreach ($this->users as $name => $user) {
            if ($name !== $from) $user->receive($from, $message);
        }
    }
}

// Colleagues: only know the mediator, never each other
class User {
    private ?ChatMediator $room = null;
    public function __construct(private string $name) {}
    public function name(): string { return $this->name; }
    public function setRoom(ChatMediator $room): void { $this->room = $room; }

    public function say(string $message, ?string $to = null): void {
        $this->room?->send($this->name, $message, $to);
    }
    public function receive(string $from, string $message): void {
        echo "[{$this->name}] <- {$from}: {$message}\n";
    }
}

$room = new ChatRoom();
$alice = new User('alice'); $bob = new User('bob'); $cat = new User('cat');
$room->register($alice); $room->register($bob); $room->register($cat);

$alice->say('hi everyone');          // broadcast
$bob->say('hi alice', 'alice');      // direct message

Why it matters

The mediator becomes a god-object if you let it accumulate business logic. Keep it strictly about routing — who talks to whom — and push domain decisions back into the colleagues. When the mediator starts to know "what" the messages mean, you have lost the win.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// One mediator coordinates many participants instead of N-to-N coupling.
// Real-world examples: chat-room hub, form orchestration, redux store.
Try it Yourself »

Discussion

Loading…