# Design patterns: Mediator

> The Mediator pattern with PHP examples

- URL: https://mautoblog.com/en/posts/design-patterns/mediator/
- Language: en
- Published: 2024-09-27
- Updated: 2026-10-14
- Author: Mauto
- Categories: Software Development, Technology
- Tags: Software Architecture, Best Practices, PHP
- Guide: Design Patterns (part 18)
- Translation (it): https://mautoblog.com/posts/design-patterns/mediator/

---
The **Mediator Pattern** is a behavioral design pattern that defines an object (the mediator) responsible for controlling communication among a set of objects. Instead of letting the objects communicate directly with each other, the mediator centralizes and manages their interaction, thereby reducing their coupling.

### When to Use It:
- When you have many objects interacting with each other and you want to avoid direct, complex dependencies between them.
- When you want to simplify communication between the objects in a system and make the code more manageable.

## Strengths
1. **Reduces Coupling:** Objects don't communicate directly with each other but through the mediator, reducing dependencies and simplifying the relationships between components.
2. **Easier Maintenance:** With fewer direct dependencies between objects, it's easier to change the behavior of a single component without affecting other objects.
3. **Centralized Communication Logic:** The communication logic is centralized in the mediator, making it easy to manage interactions among multiple objects.
4. **Increased Flexibility:** It lets you change how objects interact by modifying the mediator, without touching the individual objects.
5. **Supports Problem Decomposition:** It lets you break a complex system down into simpler parts, making the overall architecture clearer and easier to understand.

### Use Case
Imagine a chat system in which several users communicate with each other. Instead of letting users send messages directly to one another, a `ChatRoom` object acts as a centralized mediator.

### PHP Code
```php
// Interface for the Mediator
interface ChatRoomMediator {
    public function register(User $user);
    public function showMessage(User $sender, $message);
}

// Concrete Mediator
class ChatRoom implements ChatRoomMediator {
    private $users = [];

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

    // Delivers the message to every registered user except the sender
    public function showMessage(User $sender, $message) {
        foreach ($this->users as $user) {
            if ($user !== $sender) {
                $user->receive($sender->getName(), $message);
            }
        }
    }
}

// User class
class User {
    private $name;
    private $mediator;

    public function __construct($name, ChatRoomMediator $mediator) {
        $this->name = $name;
        $this->mediator = $mediator;
    }

    public function getName() {
        return $this->name;
    }

    public function sendMessage($message) {
        $this->mediator->showMessage($this, $message);
    }

    public function receive($senderName, $message) {
        echo "{$this->name} receives from {$senderName}: {$message}\n";
    }
}

// Using the Mediator
$mediator = new ChatRoom();

$user1 = new User("Alice", $mediator);
$user2 = new User("Bob", $mediator);
$user3 = new User("Charlie", $mediator);

$mediator->register($user1);
$mediator->register($user2);
$mediator->register($user3);

$user1->sendMessage("Hi everyone!");
$user2->sendMessage("Hi Alice! How are you?");

/* output
Bob receives from Alice: Hi everyone!
Charlie receives from Alice: Hi everyone!
Alice receives from Bob: Hi Alice! How are you?
Charlie receives from Bob: Hi Alice! How are you?
*/
```

## Explanation
- **ChatRoomMediator** is the interface that defines the methods for registering users (**register()**) and forwarding messages (**showMessage()**).
- **ChatRoom** is the concrete implementation of the mediator: it keeps the list of registered users and delivers each message to all the others, centralizing the communication logic.
- **User** represents the objects taking part in the chat. Users don't communicate directly with each other; they send messages through the mediator (**ChatRoom**) and receive them with the **receive()** method.
- The **ChatRoom** mediator handles the delivery of messages between users, reducing the coupling between them.

[BACK TO THE GUIDE](/en/posts/design-patterns/)
