1
+ <?php
2
+
3
+ namespace DesignPatterns ;
4
+
5
+ /**
6
+ * Decorator pattern
7
+ *
8
+ * Purpose:
9
+ * to dynamically add new functionality to class instances
10
+ *
11
+ * Examples:
12
+ * - Zend Framework: decorators for Zend_Form_Element instances
13
+ * - Web Service Layer: Decorators JSON and XML for a REST service (in this case, only one of these should be allowed of
14
+ * course)
15
+ *
16
+ */
17
+ class Webservice
18
+ {
19
+ protected $ _data ;
20
+
21
+ /**
22
+ * an array to holds all added decorators, often there would be defaults set in this
23
+ * array, e.g. the service could be defaulted to use JSON and only for special APIs
24
+ * use XML
25
+ *
26
+ * @var array
27
+ */
28
+ protected $ _decorators = array ();
29
+
30
+ public function __construct ($ data )
31
+ {
32
+ $ this ->_data = $ data ;
33
+ }
34
+
35
+ /**
36
+ *
37
+ *
38
+ * @param WebserviceDecorator $decorator
39
+ * @return void
40
+ */
41
+ public function addDecorator (WebserviceDecorator $ decorator )
42
+ {
43
+ $ this ->_decorators [] = $ decorator ;
44
+ }
45
+
46
+ /**
47
+ * @return string
48
+ */
49
+ public function renderData ()
50
+ {
51
+ $ response = '' ;
52
+ foreach ($ this ->_decorators as $ decorator ) {
53
+ $ response = $ decorator ->renderData ($ this ->_data );
54
+ }
55
+
56
+ return $ response ;
57
+ }
58
+ }
59
+
60
+ interface WebserviceDecorator
61
+ {
62
+ public function renderData ($ data );
63
+ }
64
+
65
+ class JsonDecorator implements WebserviceDecorator
66
+ {
67
+ public function renderData ($ data )
68
+ {
69
+ return json_encode ($ data );
70
+ }
71
+ }
72
+
73
+ class XmlDecorator implements WebserviceDecorator
74
+ {
75
+ public function renderData ($ data )
76
+ {
77
+ // do some fany conversion to xml from array ...
78
+ return simplexml_load_string ($ data );
79
+ }
80
+ }
81
+
82
+ $ service = new Webservice (array ('foo ' => 'bar ' ));
83
+ $ service ->addDecorator (new JsonDecorator ());
84
+ echo $ service ->renderData ();
0 commit comments