Evgenii Legotckoi
Sept. 21, 2018, 1:18 p.m.

Example - "Builder" design pattern in PHP

Content

In the Builder Pattern a director and a builder work together to build an object. The director controls the building and specifies what parts and variations will go into an object. The builder knows how to assemble the object given specification.

In this example we have a director, HTMLPageDirector, which is given a builder,  HTMLPageBuilder. The director tells the builder what the pageTitle will be, what the  pageHeading will be, and gives multiple lines of text for the page. The director then has the builder do a final assembly of the parts, and return the page.


  1. <?php
  2.  
  3. abstract class AbstractPageBuilder {
  4. abstract function getPage();
  5. }
  6.  
  7. abstract class AbstractPageDirector {
  8. abstract function __construct(AbstractPageBuilder $builder_in);
  9. abstract function buildPage();
  10. abstract function getPage();
  11. }
  12.  
  13. class HTMLPage {
  14. private $page = NULL;
  15. private $page_title = NULL;
  16. private $page_heading = NULL;
  17. private $page_text = NULL;
  18. function __construct() {
  19. }
  20. function showPage() {
  21. return $this->page;
  22. }
  23. function setTitle($title_in) {
  24. $this->page_title = $title_in;
  25. }
  26. function setHeading($heading_in) {
  27. $this->page_heading = $heading_in;
  28. }
  29. function setText($text_in) {
  30. $this->page_text .= $text_in;
  31. }
  32. function formatPage() {
  33. $this->page = '<html>';
  34. $this->page .= '<head><title>'.$this->page_title.'</title></head>';
  35. $this->page .= '<body>';
  36. $this->page .= '<h1>'.$this->page_heading.'</h1>';
  37. $this->page .= $this->page_text;
  38. $this->page .= '</body>';
  39. $this->page .= '</html>';
  40. }
  41. }
  42.  
  43. class HTMLPageBuilder extends AbstractPageBuilder {
  44. private $page = NULL;
  45. function __construct() {
  46. $this->page = new HTMLPage();
  47. }
  48. function setTitle($title_in) {
  49. $this->page->setTitle($title_in);
  50. }
  51. function setHeading($heading_in) {
  52. $this->page->setHeading($heading_in);
  53. }
  54. function setText($text_in) {
  55. $this->page->setText($text_in);
  56. }
  57. function formatPage() {
  58. $this->page->formatPage();
  59. }
  60. function getPage() {
  61. return $this->page;
  62. }
  63. }
  64.  
  65. class HTMLPageDirector extends AbstractPageDirector {
  66. private $builder = NULL;
  67. public function __construct(AbstractPageBuilder $builder_in) {
  68. $this->builder = $builder_in;
  69. }
  70. public function buildPage() {
  71. $this->builder->setTitle('Testing the HTMLPage');
  72. $this->builder->setHeading('Testing the HTMLPage');
  73. $this->builder->setText('Testing, testing, testing!');
  74. $this->builder->setText('Testing, testing, testing, or!');
  75. $this->builder->setText('Testing, testing, testing, more!');
  76. $this->builder->formatPage();
  77. }
  78. public function getPage() {
  79. return $this->builder->getPage();
  80. }
  81. }
  82.  
  83. writeln('BEGIN TESTING BUILDER PATTERN');
  84. writeln('');
  85.  
  86. $pageBuilder = new HTMLPageBuilder();
  87. $pageDirector = new HTMLPageDirector($pageBuilder);
  88. $pageDirector->buildPage();
  89. $page = $pageDirector->getPage();
  90. writeln($page->showPage());
  91. writeln('');
  92.  
  93. writeln('END TESTING BUILDER PATTERN');
  94.  
  95. function writeln($line_in) {
  96. echo $line_in."<br/>";
  97. }
  98.  
  99. ?>

Output

  1. BEGIN TESTING BUILDER PATTERN
  2.  
  3. <html>
  4. <head><title>Testing the HTMLPage</title></head>
  5. <body>
  6. <h1>Testing the HTMLPage</h1>
  7. Testing, testing, testing!
  8. Testing, testing, testing, or!
  9. Testing, testing, testing, more!
  10. </body>
  11. </html>
  12.  
  13. END TESTING BUILDER PATTERN

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html