-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFactoryMethod.php
89 lines (75 loc) · 1.83 KB
/
FactoryMethod.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
<?php
namespace DesignPatterns\Creational;
/**
* Base factory class contains a factory method and some business logic
*/
abstract class Response
{
protected $data;
public function __construct(string $data)
{
$formatter = $this->createFormatter();
$this->data = $formatter->wrapData($data);
}
/**
* Factory Method, usually abstract
* but it can also return a certain standard product (formatter)
*/
abstract function createFormatter(): Formatter;
public function __toString()
{
return $this->data;
}
}
/**
* Concrete factories extend that method to produce different kinds of response
*/
class JSONResponse extends Response
{
public function createFormatter(): Formatter
{
return new JSONFormatter();
}
}
class HTMLResponse extends Response
{
public function createFormatter(): Formatter
{
return new HTMLFormatter();
}
}
/**
* Formatter interface declares behaviors of various types of response
*/
interface Formatter
{
public function wrapData(string $data): string;
}
class HTMLFormatter implements Formatter
{
public function wrapData(string $data): string
{
return '<html>' . $data . '</html>';
}
}
class JSONFormatter implements Formatter
{
public function wrapData(string $data): string
{
return '{"code": 200, "response": "' . $data . '"}';
}
}
# Client code example
$data = 'some input data';
$responseFormat = 'json'; // taken from configuration for example
$response = '';
switch ($responseFormat) {
case 'json':
$response = new JsonResponse($data); // will use JSONFormatter
break;
case 'html':
$response = new HTMLResponse($data); // will use HTMLFormatter
break;
}
echo $response;
/* Output: {"code": 200, "response": "some input data"} */