Application 2019-01-31

Learning Design Patterns with PHP - Mediator Pattern

Explore the Mediator pattern to coordinate complex interactions between objects and improve relationship visibility in PHP.

Read in: ja
Learning Design Patterns with PHP - Mediator Pattern

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.

References

Tags: PHP Design Patterns Mediator Pattern GoF
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles