-
Notifications
You must be signed in to change notification settings - Fork 2
/
Command.php
92 lines (78 loc) · 1.6 KB
/
Command.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
<?php
namespace DesignPatterns\Behavioral;
/**
* Abstract command
*/
abstract class Command
{
protected $receiver;
public function __construct(Receiver $receiver)
{
$this->receiver = $receiver;
}
public abstract function execute();
}
/**
* Concrete command, doesn't do all the work by self and only passes the call to the receiver
*/
class TurnOnCommand extends Command
{
public function execute()
{
$this->receiver->turnOn();
}
}
class TurnOffCommand extends Command
{
public function execute()
{
$this->receiver->turnOff();
}
}
/**
* Invoker of commands
*/
class Invoker
{
/**
* @var []Command Queue of commands
*/
protected $commands = [];
public function pushCommand(Command $command)
{
$this->commands[] = $command;
}
/**
* Executes all commands from queue
*/
public function execute()
{
foreach ($this->commands as $key => $command) {
$command->execute();
unset($this->commands[$key]);
}
}
}
/**
* Receiver of commands, contains some business logic
*/
class Receiver
{
public function turnOn()
{
echo "Receiver: Turning on something..\n";
}
public function turnOff()
{
echo "Receiver: Turning off something..\n";
}
}
# Client code example
$invoker = new Invoker();
$receiver = new Receiver();
$invoker->pushCommand(new TurnOnCommand($receiver));
$invoker->pushCommand(new TurnOffCommand($receiver));
$invoker->execute();
/* Output:
Receiver: Turning on something..
Receiver: Turning off something.. */