-
Notifications
You must be signed in to change notification settings - Fork 2
/
BuilderExt.php
90 lines (73 loc) · 1.76 KB
/
BuilderExt.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
<?php
namespace DesignPatterns\Creational;
/**
* Extended example of Builder design pattern with Director
*/
class Page
{
public $title;
public $header;
public $content;
public $footer;
public function show(): string
{
$result = $this->title;
$result .= $this->header;
$result .= $this->content;
$result .= $this->footer;
return $result;
}
}
class Director
{
protected $builder;
public function __construct(Builder $builder)
{
$this->builder = $builder;
}
/**
* Tells the builder what to do (desired sequence)
*/
public function construct()
{
$this->builder->addHeader('header');
$this->builder->addContent('content');
$this->builder->addFooter('footer');
}
}
abstract class Builder
{
abstract public function addHeader(string $header);
abstract public function addContent(string $content);
abstract public function addFooter(string $footer);
}
class HTMLPageBuilder extends Builder
{
/**
* @var Page
*/
private $page;
public function __construct(Page $page)
{
$this->page = $page;
}
public function addHeader(string $header)
{
$this->page->header = '<header>' . $header . '</header>';
}
public function addContent(string $content)
{
$this->page->content = '<article>' . $content . '</article>';
}
public function addFooter(string $footer)
{
$this->page->footer = '<footer>' . $footer . '</footer>';
}
}
# Client code example
$page = new Page();
$director = new Director(new HTMLPageBuilder($page));
$director->construct();
echo $page->show();
/* Output:
<header>header</header><article>content</article><footer>footer</footer> */