3.4. Mediator
All components (called Colleague) are only coupled to theMediatorInterface and it is a good thing because in OOP, one good friendis better than many. This is the key-feature of this pattern.
MediatorInterface.php
Mediator.php
- <?php
- namespace DesignPatterns\Behavioral\Mediator;
- /**
- * Mediator is the concrete Mediator for this design pattern
- *
- * In this example, I have made a "Hello World" with the Mediator Pattern
- */
- class Mediator implements MediatorInterface
- {
- /**
- * @var Subsystem\Server
- */
- private $server;
- /**
- * @var Subsystem\Database
- */
- private $database;
- /**
- * @var Subsystem\Client
- */
- private $client;
- /**
- * @param Subsystem\Database $database
- * @param Subsystem\Server $server
- */
- public function __construct(Subsystem\Database $database, Subsystem\Client $client, Subsystem\Server $server)
- {
- $this->database = $database;
- $this->server = $server;
- $this->client = $client;
- $this->database->setMediator($this);
- $this->server->setMediator($this);
- $this->client->setMediator($this);
- }
- public function makeRequest()
- {
- $this->server->process();
- }
- public function queryDb(): string
- {
- return $this->database->getData();
- }
- /**
- * @param string $content
- */
- public function sendResponse($content)
- {
- $this->client->output($content);
- }
- }
Subsystem/Client.php
- <?php
- namespace DesignPatterns\Behavioral\Mediator\Subsystem;
- use DesignPatterns\Behavioral\Mediator\Colleague;
- /**
- * Client is a client that makes requests and gets the response.
- */
- class Client extends Colleague
- {
- public function request()
- {
- $this->mediator->makeRequest();
- }
- public function output(string $content)
- {
- echo $content;
- }
- }
Subsystem/Database.php
- <?php
- namespace DesignPatterns\Behavioral\Mediator\Subsystem;
- use DesignPatterns\Behavioral\Mediator\Colleague;
- class Server extends Colleague
- {
- public function process()
- {
- $data = $this->mediator->queryDb();
- $this->mediator->sendResponse(sprintf("Hello %s", $data));
- }
Tests/MediatorTest.php