forked from Djuki/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStatusPattern.php
More file actions
127 lines (101 loc) · 2.38 KB
/
StatusPattern.php
File metadata and controls
127 lines (101 loc) · 2.38 KB
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
<?php
namespace DesignPatterns;
/**
* The order has two status: created, shipping, completed.
* When the order's status is created, what can do is just 'shipping' handle;
* When the order's status is shipping, what can do is just 'completed' handle;
*
*/
interface OrderInterface
{
public function shipOrder();
public function completeOrder();
}
class CreateOrder implements OrderInterface
{
private $order;
public function __construct(array $order)
{
if (empty($order)) {
throw new \Exception('Order can not be empty!');
}
$this->order = $order;
}
public function shipOrder()
{
$this->order['status'] = 'shipping';
$this->order['updatedTime'] = time();
// Setting the new order status into database;
return $this->updateOrder($order);
}
public function completeOrder()
{
//Can not complete the order which status is created, throw exception;
throw new \Exception('Can not complete the order which status is created!');
}
}
class ShippingOrder implements OrderInterface
{
private $order;
public function __construct(array $order)
{
if (empty($order)) {
throw new \Exception('Order can not be empty!');
}
$this->order = $order;
}
public function shipOrder()
{
//Can not ship the order which status is shipping, throw exception;
throw new \Exception('Can not ship the order which status is shipping!');
}
public function completeOrder()
{
$this->order['status'] = 'completed';
$this->order['updatedTime'] = time();
// Setting the new order status into database;
return $this->updateOrder($order);
}
}
class OrderFactory {
public static function getOrder($id)
{
$order = 'Get Order From Database';
switch ($order['status']) {
case 'created':
return new CreateOrder($order);
case 'shipping':
return new ShippingOrder($order);
default:
throw new \Exception('Order status error!');
break;
}
}
private function __construct()
{
throw Exception('Can not instance the OrderFactory class!');
}
}
// Client
Class OrderControler {
public function shipAction($id)
{
$order = OrderFactory::getOrder($id);
try {
$order->shipOrder($id);
} catch (Exception $e) {
//handle error!
}
// response to browser
}
public function completeAction($id)
{
$order = OrderFactory::getOrder($id);
try {
$order->completeOrder($id);
} catch (Exception $e) {
//handle error!
}
// response to browser
}
}