-
Notifications
You must be signed in to change notification settings - Fork 45
/
Decorator.php
84 lines (76 loc) · 2.12 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
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/**
* Decorator design pattern (example of implementation)
*
* @author Enrico Zimuel ([email protected])
* @see http://en.wikipedia.org/wiki/Decorator_pattern
* @see http://www.giorgiosironi.com/2010/01/practical-php-patterns-decorator.html
*/
interface HtmlElement
{
public function __toString();
public function getName();
}
class InputText implements HtmlElement
{
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function __toString() {
return "<input type=\"text\" id=\"{$this->name}\" name=\"{$this->name}\" />\n";
}
}
abstract class HtmlDecorator implements HtmlElement
{
protected $element;
public function __construct(HtmlElement $input) {
$this->element = $input;
}
public function getName() {
return $this->element->getName();
}
public function __toString() {
return $this->element->__toString();
}
}
class LabelDecorator extends HtmlDecorator
{
protected $label;
public function setLabel($label) {
$this->label = $label;
}
public function __toString() {
$name = $this->getName();
return "<label for=\"{$name}\">{$this->label}</label>\n"
. $this->element->__toString();
}
}
class ErrorDecorator extends HtmlDecorator
{
protected $error;
public function setError($message) {
$this->error = $message;
}
public function __toString() {
return $this->element->__toString() . "<span>{$this->error}</span>\n";
}
}
$input = new InputText('nickname');
$labelled = new LabelDecorator($input);
$labelled->setLabel('Nickname:');
printf("%s\n", $labelled);
$input = new InputText('nickname');
$error = new ErrorDecorator($input);
$error->setError('You must enter a unique nickname');
printf("%s\n", $error);
// Label + Error
$input = new InputText('nickname');
$labelled = new LabelDecorator($input);
$labelled->setLabel('Nickname:');
$error = new ErrorDecorator($labelled);
$error->setError('You must enter a unique nickname');
printf("%s\n", $error);