forked from lcp0578/design-patterns-in-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Decorator.php
72 lines (60 loc) · 1.26 KB
/
Decorator.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
<?php
/**
* Decorator
*/
class HtmlTemplate
{
//any parent methods
}
class Template1 extends HtmlTemplate
{
protected $_html;
public function __construct(){
$this->_html = "<p>__text__</p>";
}
public function set($html){
$this->_html = $html;
}
public function render(){
echo $this->_html .PHP_EOL;
}
}
class Template2 extends HtmlTemplate
{
protected $_element;
protected $_html;
public function __construct($ele, $html){
$this->_element = $ele;
$this->_html = $html;
$this->set('<h2>' . $this->_html . '</h2>');
}
public function __call($name, $args){
$param = implode(',', $args);
$this->_element->$name($param);
}
}
class Template3 extends HtmlTemplate
{
protected $_element;
public function __construct($ele, $html){
$this->_element = $ele;
$this->_html = $html;
$this->set('<ul>' . $this->_html . '</ul>');
}
public function __call($name, $args){
$param = implode(',', $args);
$this->_element->$name($param);
}
}
$tpl1 = new Template1();
$tpl1->render();
$tpl1->set('Hello Decorator!');
$tpl1->render();
$tpl2 = new Template2($tpl1, 'Hello TPL 2');
$tpl2->render();
$tpl2->set('Hello TPL 2 agian');
$tpl2->render();
$tpl2 = new Template3($tpl1, 'Hello TPL 3');
$tpl2->render();
$tpl2->set('Hello TPL 3 agian');
$tpl2->render();