/
Command.php
103 lines (86 loc) · 2.12 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
93
94
95
96
97
98
99
100
101
102
103
<?php
/**
* Class CommandContext
*/
class CommandContext
{
private $params = [];
private $error = "";
function __construct()
{
$this->params = $_REQUEST;
}
function addParam($key, $val)
{
$this->params[$key] = $val;
}
function get($key)
{
return $this->params[$key];
}
function setError($error)
{
$this->error = $error;
}
function getError()
{
return $this->error;
}
}
/**
* Class CommandFactory
*/
class CommandFactory
{
private static $dir = 'commands';
static function getCommand($action = 'Default')
{
if (preg_match('/\W/', $action)) {
throw new Exception("Недопустимые символы в команде");
}
$class = UCFirst(strtolower($action)) . "Command";
$file = self::$dir . DIRECTORY_SEPARATOR . "{$class}.php";
if (!file_exists($file)) {
throw new CommandNotFoundException("Файл '$file' не найден");
}
require_once($file);
if (!class_exists($class)) {
throw new CommandNotFoundException("Класс '$class' необнаружен");
}
$cmd = new $class();
return $cmd;
}
}
/**
* Class Controller
*/
class Controller
{
private $context;
function __construct()
{
$this->context = new CommandContext();
}
function getContext()
{
return $this->context;
}
function process()
{
$cmd = CommandFactory::getCommand($this->context->get('action'));
if (!$cmd->execute($this->context)) {
echo "Обработка ошибки: ";
echo $this->context->getError();;
} else {
//Все прошло успешно
echo "Отображаем результат";
}
}
}
$controller = new Controller();
// Эмулируем запрос пользователя
$context = $controller->getContext();
$context->addParam('action', 'login');
$context->addParam('username', 'bob');
$context->addParam('pass', 'tiddles');
$controller->process();