PageRenderTime 53ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/Decorator.php

https://github.com/turnaev/PHP-design-patterns
PHP | 84 lines | 68 code | 8 blank | 8 comment | 0 complexity | a80361eefe9f44653e6976c8c99f0940 MD5 | raw file
  1. <?php
  2. /**
  3. * Decorator design pattern (example of implementation)
  4. *
  5. * @author Enrico Zimuel (enrico@zimuel.it)
  6. * @see http://en.wikipedia.org/wiki/Decorator_pattern
  7. * @see http://www.giorgiosironi.com/2010/01/practical-php-patterns-decorator.html
  8. */
  9. interface HtmlElement
  10. {
  11. public function __toString();
  12. public function getName();
  13. }
  14. class InputText implements HtmlElement
  15. {
  16. protected $name;
  17. public function __construct($name) {
  18. $this->name = $name;
  19. }
  20. public function getName() {
  21. return $this->name;
  22. }
  23. public function __toString() {
  24. return "<input type=\"text\" id=\"{$this->name}\" name=\"{$this->name}\" />\n";
  25. }
  26. }
  27. abstract class HtmlDecorator implements HtmlElement
  28. {
  29. protected $element;
  30. public function __construct(HtmlElement $input) {
  31. $this->element = $input;
  32. }
  33. public function getName() {
  34. return $this->element->getName();
  35. }
  36. public function __toString() {
  37. return $this->element->__toString();
  38. }
  39. }
  40. class LabelDecorator extends HtmlDecorator
  41. {
  42. protected $label;
  43. public function setLabel($label) {
  44. $this->label = $label;
  45. }
  46. public function __toString() {
  47. $name = $this->getName();
  48. return "<label for=\"{$name}\">{$this->label}</label>\n"
  49. . $this->element->__toString();
  50. }
  51. }
  52. class ErrorDecorator extends HtmlDecorator
  53. {
  54. protected $error;
  55. public function setError($message) {
  56. $this->error = $message;
  57. }
  58. public function __toString() {
  59. return $this->element->__toString() . "<span>{$this->error}</span>\n";
  60. }
  61. }
  62. $input = new InputText('nickname');
  63. $labelled = new LabelDecorator($input);
  64. $labelled->setLabel('Nickname:');
  65. printf("%s\n", $labelled);
  66. $input = new InputText('nickname');
  67. $error = new ErrorDecorator($input);
  68. $error->setError('You must enter a unique nickname');
  69. printf("%s\n", $error);
  70. // Label + Error
  71. $input = new InputText('nickname');
  72. $labelled = new LabelDecorator($input);
  73. $labelled->setLabel('Nickname:');
  74. $error = new ErrorDecorator($labelled);
  75. $error->setError('You must enter a unique nickname');
  76. printf("%s\n", $error);