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

    1. <?php
    2.  
    3. namespace DesignPatterns\Behavioral\Mediator;
    4.  
    5. /**
    6. * Mediator is the concrete Mediator for this design pattern
    7. *
    8. * In this example, I have made a "Hello World" with the Mediator Pattern
    9. */
    10. class Mediator implements MediatorInterface
    11. {
    12. /**
    13. * @var Subsystem\Server
    14. */
    15. private $server;
    16.  
    17. /**
    18. * @var Subsystem\Database
    19. */
    20. private $database;
    21.  
    22. /**
    23. * @var Subsystem\Client
    24. */
    25. private $client;
    26.  
    27. /**
    28. * @param Subsystem\Database $database
    29. * @param Subsystem\Server $server
    30. */
    31. public function __construct(Subsystem\Database $database, Subsystem\Client $client, Subsystem\Server $server)
    32. {
    33. $this->database = $database;
    34. $this->server = $server;
    35. $this->client = $client;
    36.  
    37. $this->database->setMediator($this);
    38. $this->server->setMediator($this);
    39. $this->client->setMediator($this);
    40. }
    41.  
    42. public function makeRequest()
    43. {
    44. $this->server->process();
    45. }
    46.  
    47. public function queryDb(): string
    48. {
    49. return $this->database->getData();
    50. }
    51.  
    52. /**
    53. * @param string $content
    54. */
    55. public function sendResponse($content)
    56. {
    57. $this->client->output($content);
    58. }
    59. }

    Subsystem/Client.php

    1. <?php
    2. namespace DesignPatterns\Behavioral\Mediator\Subsystem;
    3.  
    4. use DesignPatterns\Behavioral\Mediator\Colleague;
    5.  
    6. /**
    7. * Client is a client that makes requests and gets the response.
    8. */
    9. class Client extends Colleague
    10. {
    11. public function request()
    12. {
    13. $this->mediator->makeRequest();
    14. }
    15.  
    16. public function output(string $content)
    17. {
    18. echo $content;
    19. }
    20. }

    Subsystem/Database.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Behavioral\Mediator\Subsystem;
    4.  
    5. use DesignPatterns\Behavioral\Mediator\Colleague;
    6.  
    7. class Server extends Colleague
    8. {
    9. public function process()
    10. {
    11. $data = $this->mediator->queryDb();
    12. $this->mediator->sendResponse(sprintf("Hello %s", $data));
    13. }

    Tests/MediatorTest.php