-
Notifications
You must be signed in to change notification settings - Fork 2
/
AbstractFactory.php
108 lines (93 loc) · 2.11 KB
/
AbstractFactory.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
<?php
namespace DesignPatterns\Creational;
/**
* Abstract Factory defines an interface for creating all distinct products,
* but leaves the actual product creation to concrete factory classes
*/
interface TemplateFactory
{
public function createHeader(): Header;
public function createBody(): Body;
}
/**
* Each factory type corresponds to a certain product variety
*/
class SmartyTemplateFactory implements TemplateFactory
{
public function createHeader(): Header
{
return new SmartyHeader();
}
public function createBody(): Body
{
return new SmartyBody();
}
}
class BladeTemplateFactory implements TemplateFactory
{
public function createHeader(): Header
{
return new BladeHeader();
}
public function createBody(): Body
{
return new BladeBody();
}
}
/**
* The base interface for header (products) family
*/
interface Header
{
public function render(): string;
}
class SmartyHeader implements Header
{
public function render(): string
{
return '<h1>{$title}</h1>';
}
}
class BladeHeader implements Header
{
public function render(): string
{
return '<h1>{{ $title }}</h1>';
}
}
/**
* Another products family
*/
interface Body
{
public function render(): string;
}
class SmartyBody implements Body
{
public function render(): string
{
return '<main>{$content}</main>';
}
}
class BladeBody implements Body
{
public function render(): string
{
return '<main>{{ $content }}</main>';
}
}
# Client code example
// the factory is selected based on the environment or configuration parameters
$templateEngine = 'blade';
switch ($templateEngine) {
case 'smarty':
$templateFactory = new SmartyTemplateFactory();
break;
case 'blade':
$templateFactory = new BladeTemplateFactory();
break;
}
// we will have header and body as either Smarty or Blade template, but never mixed
echo $templateFactory->createHeader()->render();
echo $templateFactory->createBody()->render();
/* Output: <h1>{{ $title }}</h1><main>{{ $content }}</main> */