-
Notifications
You must be signed in to change notification settings - Fork 4
/
chains_of_responsibility.php
79 lines (66 loc) · 1.64 KB
/
chains_of_responsibility.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
<?php
/**
* Chain of Responsibility pattern example
*
* @author Christian Bergau <[email protected]>
* @copyright Free for all
* @link http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
*/
abstract class Logger
{
const ERR = 3;
const NOTICE = 5;
const DEBUG = 7;
protected $mask;
/**
* @var Logger
*/
protected $next;
public function __construct($mask)
{
$this->mask = $mask;
}
public function setNext(Logger $log)
{
$this->next = $log;
}
public function message($msg, $priority)
{
if ($priority <= $this->mask) {
$this->writeMessage($msg);
}
if ($this->next != null) {
$this->next->message($msg, $priority);
}
}
abstract protected function writeMessage($msg);
}
class StdoutLogger extends Logger
{
protected function writeMessage($msg)
{
echo 'Sending to Stdout: ' . $msg . PHP_EOL;
}
}
class EmailLogger extends Logger
{
protected function writeMessage($msg)
{
echo "Sending via email: " . $msg . PHP_EOL;
}
}
class StderrLogger extends Logger
{
protected function writeMessage($msg)
{
echo "Sending to stderr: " . $msg . PHP_EOL;
}
}
// Create the chain
$chainLogger = new StdoutLogger(Logger::DEBUG);
$emailLogger = new EmailLogger(Logger::NOTICE);
$chainLogger->setNext($emailLogger);
$emailLogger->setNext(new StderrLogger(Logger::ERR));
$chainLogger->message("Entering function y.", Logger::DEBUG);
$chainLogger->message("Step1 completed.", Logger::NOTICE);
$chainLogger->message("An error has occurred.", Logger::ERR);