-
Notifications
You must be signed in to change notification settings - Fork 2
/
CommandExt.php
118 lines (99 loc) · 2.5 KB
/
CommandExt.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
<?php
namespace DesignPatterns\Behavioral;
/**
* Abstract command
*/
abstract class CommandExtended
{
protected $receiver;
protected $params;
/**
* Constructor
* @param Receiver $receiver Receiver of command
* @param mixed ...$params Parameters that may be needed to Receiver
*/
public function __construct(Receiver $receiver, ...$params)
{
$this->receiver = $receiver;
$this->params = $params;
}
/**
* We should have possibility to execute command and rollback if necessary
*/
public abstract function execute();
public abstract function rollback();
}
/**
* Concrete command, doesn't do all the work by self and only passes the call to the receiver
*/
class TurnOnCommand extends CommandExtended
{
public function execute()
{
$this->receiver->turnOn($this->params);
}
public function rollback()
{
$this->receiver->turnoff($this->params);
}
}
/*
* Invoker of commands
*/
class Invoker
{
/**
* @var []Command Queue of commands
*/
protected $commands = [];
public function pushCommand(CommandExtended $command)
{
return array_push($this->commands, $command);
}
/**
* Executes last command
*/
public function executeCommand()
{
/** @var CommandExtended $lastCommand */
if ($lastCommand = array_pop($this->commands)) {
return $lastCommand->execute();
}
return false;
}
/**
* Rollbacks last command
*/
public function rollbackCommand()
{
/** @var CommandExtended $lastCommand */
if ($lastCommand = array_pop($this->commands)) {
return $lastCommand->rollback();
}
return false;
}
}
/**
* Receiver of commands, contains some business logic
*/
class Receiver
{
public function turnOn($params)
{
echo "Receiver: Turning on something with params: " . implode(', ', $params) . PHP_EOL;
}
public function turnOff($params)
{
echo "Receiver: Turning off something with params: " . implode(', ', $params) . PHP_EOL;
}
}
# Client code example
$invoker = new Invoker();
$receiver = new Receiver();
$invoker->pushCommand(new TurnOnCommand($receiver, 'some_param'));
$invoker->executeCommand();
$invoker->pushCommand(new TurnOnCommand($receiver, 'kill', -9));
$invoker->rollbackCommand();
/* Output:
Receiver: Turning on something with params: some_param
Receiver: Turning off something with params: kill, -9 */