-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathChainOfResponsibility.php
148 lines (127 loc) · 2.77 KB
/
ChainOfResponsibility.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
<?php
namespace DesignPatterns\Behavioral;
/**
* Declares a basic method for building the chain of handlers and method for executing a request
*/
interface Handler
{
public function setNext(Handler $handler);
public function handle($message);
}
/**
* An optional class that eliminates the duplication of the same code in all specific handlers
*/
abstract class AbstractLogger implements Handler
{
/**
* @var Handler
*/
private $nextHandler;
/**
* Sets next handler and returns its instance
* @param Handler $handler
* @return Handler
*/
public function setNext(Handler $handler)
{
$this->nextHandler = $handler;
// it will let us link handlers in a convenient way like: $handler->setNext()->setNext()
return $handler;
}
/**
* Calls next handler if present
* @param $message
* @return bool
*/
public function handle($message)
{
if ($this->nextHandler) {
return $this->nextHandler->handle($message);
}
return false;
}
}
/**
* Logs message to database if possible and execute next handler
*/
class DBLogger extends AbstractLogger
{
/**
* Stub method
* @return bool
*/
public function canSave()
{
// you can play with true/false value
return false;
}
public function handle($message)
{
if ($this->canSave()) {
echo "Save message to database..\n";
}
return parent::handle($message);
}
}
/**
* Sends message by mail if possible and executes next handler
*/
class MailLogger extends AbstractLogger
{
/**
* Stub method
* @return bool
*/
public function canMail()
{
return true;
}
public function handle($message)
{
if ($this->canMail()) {
echo 'Send message by email..' . PHP_EOL;
}
return parent::handle($message);
}
}
/**
* Logs message to log file if possible and executes next handler if present
*/
class FileLogger extends AbstractLogger
{
/**
* Stub method
* @return bool
*/
public function canWrite()
{
return true;
}
public function handle($message)
{
if ($this->canWrite()) {
echo "Save message to log file..\n";
}
return parent::handle($message);
}
}
# Client code example
/**
* Simple logger
*/
class Logger
{
public static function log($message)
{
// build the chain
$logger = new DBLogger();
$logger->setNext(new MailLogger())
->setNext(new FileLogger());
// call the first handler
$logger->handle($message);
}
}
Logger::log('Message text');
/* Output:
Send message by email..
Save message to log file.. */