-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBuilder.php
77 lines (63 loc) · 1.63 KB
/
Builder.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
<?php
namespace DesignPatterns\Creational;
/**
* The main idea behind Builder pattern is prevent "telescoping constructor"
* public function __construct($name, $value, $param1 = true, $param2 = true, $param3 = false, ..) {}
*/
class Page
{
public $title;
public $header;
public $content;
public $footer;
public function __construct(PageBuilder $builder)
{
$this->title = $builder->title;
$this->header = $builder->header;
$this->content = $builder->content;
$this->footer = $builder->footer;
}
public function show(): string
{
return $this->title . $this->header . $this->content . $this->footer;
}
}
class PageBuilder
{
public $title;
public $header = '';
public $content = '';
public $footer = '';
public function __construct(string $title)
{
$this->title = $title;
}
public function addHeader(string $header)
{
$this->header = $header;
return $this;
}
public function addContent(string $content)
{
$this->content = $content;
return $this;
}
public function addFooter(string $footer)
{
$this->footer = $footer;
return $this;
}
public function build(): Page
{
return new Page($this);
}
}
# Client code example
$page = (new PageBuilder('<h1>Home page</h1>'))
->addHeader('<header></header>')
->addContent('<article>content</article>');
// some time letter ..
$page->addFooter('<footer></footer>');
echo $page->build()->show();
/* Output:
<h1>Home page</h1><header></header><article>content</article><footer></footer> */