-
Notifications
You must be signed in to change notification settings - Fork 2
/
Mediator.php
89 lines (76 loc) · 2.06 KB
/
Mediator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
namespace DesignPatterns\Behavioral;
/**
* General interface of mediators
*/
interface Mediator
{
public function notify($sender, $event, $data);
}
/**
* Concrete Mediator receives notices from components and knows how to react to them
* @package DesignPatterns\Behavioral
*/
class ChatMediator implements Mediator
{
/**
* When something happens, component sends an notification to the mediator.
* After receiving the notification, the mediator can either do something on his own, or redirect
* the request to another component.
*/
public function notify($sender, $event, $data)
{
if ($sender instanceof User && $event == 'sendMessage') {
echo "{$sender->name}: $data->message\n";
} elseif ($sender instanceof Bot && $event == 'banUser') {
echo "User {$data->name} was banned by {$sender->name}";
}
}
}
/**
* Concrete components are not directly related.
* There is only one channel of communication - by sending notifications to the mediator.
*/
class User
{
public $name;
protected $mediator;
public function __construct(string $name, Mediator $mediator)
{
$this->name = $name;
$this->mediator = $mediator;
}
public function sendMessage(string $message)
{
$data = new \stdClass();
$data->message = $message;
$this->mediator->notify($this, 'sendMessage', $data);
}
}
class Bot
{
public $name = 'Bot';
protected $mediator;
public function __construct(Mediator $mediator)
{
$this->mediator = $mediator;
}
public function banUser(User $user)
{
$this->mediator->notify($this, 'banUser', $user);
}
}
# Client code example
$chat = new ChatMediator();
$john = new User('John', $chat);
$jane = new User('Jane', $chat);
$bot = new Bot($chat);
// every chat member interacts with mediator,
// but not with with each other directly
$john->sendMessage("Hi!");
$jane->sendMessage("What's up?");
$bot->banUser($john);
/* Output:
John: Hi!
Jane: What's up?
User John was banned by Bot */