Evgenii Legotckoi
Sept. 25, 2018, 4:16 p.m.

Example - Factory method in PHP

Content

In the Factory Method Pattern, a factory method defines what functions must be available in the non-abstract or concrete factory. These functions must be able to create objects that are extensions of a specific class. Which exact subclass is created will depend on the value of a parameter passed to the function.

В этом примере у нас есть фабричный метод AbstractFactoryMethod , который задает функцию makePHPBook($param) .

Конкретный класс OReillyFactoryMethod factory расширяет AbstractFactoryMethod и может создать правильное расширение класса AbstractPHPBook для заданного значения $ param.


  1. Конкретный класс OReillyFactoryMethod factory расширяет AbstractFactoryMethod и может создать правильное расширение класса AbstractPHPBook для заданного значения $ param.<?php
  2.  
  3. abstract class AbstractFactoryMethod {
  4. abstract function makePHPBook($param);
  5. }
  6.  
  7. class OReillyFactoryMethod extends AbstractFactoryMethod {
  8. private $context = "OReilly";
  9. function makePHPBook($param) {
  10. $book = NULL;
  11. switch ($param) {
  12. case "us":
  13. $book = new OReillyPHPBook;
  14. break;
  15. case "other":
  16. $book = new SamsPHPBook;
  17. break;
  18. default:
  19. $book = new OReillyPHPBook;
  20. break;
  21. }
  22. return $book;
  23. }
  24. }
  25.  
  26. class SamsFactoryMethod extends AbstractFactoryMethod {
  27. private $context = "Sams";
  28. function makePHPBook($param) {
  29. $book = NULL;
  30. switch ($param) {
  31. case "us":
  32. $book = new SamsPHPBook;
  33. break;
  34. case "other":
  35. $book = new OReillyPHPBook;
  36. break;
  37. case "otherother":
  38. $book = new VisualQuickstartPHPBook;
  39. break;
  40. default:
  41. $book = new SamsPHPBook;
  42. break;
  43. }
  44. return $book;
  45. }
  46. }
  47.  
  48. abstract class AbstractBook {
  49. abstract function getAuthor();
  50. abstract function getTitle();
  51. }
  52.  
  53. abstract class AbstractPHPBook {
  54. private $subject = "PHP";
  55. }
  56.  
  57. class OReillyPHPBook extends AbstractPHPBook {
  58. private $author;
  59. private $title;
  60. private static $oddOrEven = 'odd';
  61. function __construct() {
  62. //alternate between 2 books
  63. if ('odd' == self::$oddOrEven) {
  64. $this->author = 'Rasmus Lerdorf and Kevin Tatroe';
  65. $this->title = 'Programming PHP';
  66. self::$oddOrEven = 'even';
  67. } else {
  68. $this->author = 'David Sklar and Adam Trachtenberg';
  69. $this->title = 'PHP Cookbook';
  70. self::$oddOrEven = 'odd';
  71. }
  72. }
  73. function getAuthor() {return $this->author;}
  74. function getTitle() {return $this->title;}
  75. }
  76.  
  77. class SamsPHPBook extends AbstractPHPBook {
  78. private $author;
  79. private $title;
  80. function __construct() {
  81. //alternate randomly between 2 books
  82. mt_srand((double)microtime()*10000000);
  83. $rand_num = mt_rand(0,1);
  84.  
  85. if (1 > $rand_num) {
  86. $this->author = 'George Schlossnagle';
  87. $this->title = 'Advanced PHP Programming';
  88. } else {
  89. $this->author = 'Christian Wenz';
  90. $this->title = 'PHP Phrasebook';
  91. }
  92. }
  93. function getAuthor() {return $this->author;}
  94. function getTitle() {return $this->title;}
  95. }
  96.  
  97. class VisualQuickstartPHPBook extends AbstractPHPBook {
  98. private $author;
  99. private $title;
  100. function __construct() {
  101. $this->author = 'Larry Ullman';
  102. $this->title = 'PHP for the World Wide Web';
  103. }
  104. function getAuthor() {return $this->author;}
  105. function getTitle() {return $this->title;}
  106. }
  107.  
  108. writeln('START TESTING FACTORY METHOD PATTERN');
  109. writeln('');
  110.  
  111. writeln('testing OReillyFactoryMethod');
  112. $factoryMethodInstance = new OReillyFactoryMethod;
  113. testFactoryMethod($factoryMethodInstance);
  114. writeln('');
  115.  
  116. writeln('testing SamsFactoryMethod');
  117. $factoryMethodInstance = new SamsFactoryMethod;
  118. testFactoryMethod($factoryMethodInstance);
  119. writeln('');
  120.  
  121. writeln('END TESTING FACTORY METHOD PATTERN');
  122. writeln('');
  123.  
  124. function testFactoryMethod($factoryMethodInstance) {
  125. $phpUs = $factoryMethodInstance->makePHPBook("us");
  126. writeln('us php Author: '.$phpUs->getAuthor());
  127. writeln('us php Title: '.$phpUs->getTitle());
  128.  
  129. $phpUs = $factoryMethodInstance->makePHPBook("other");
  130. writeln('other php Author: '.$phpUs->getAuthor());
  131. writeln('other php Title: '.$phpUs->getTitle());
  132.  
  133. $phpUs = $factoryMethodInstance->makePHPBook("otherother");
  134. writeln('otherother php Author: '.$phpUs->getAuthor());
  135. writeln('otherother php Title: '.$phpUs->getTitle());
  136. }
  137.  
  138. function writeln($line_in) {
  139. echo $line_in."<br/>";
  140. }
  141. ?>

Output

  1. START TESTING FACTORY METHOD PATTERN
  2.  
  3. testing OReillyFactoryMethod
  4. us php Author: Rasmus Lerdorf and Kevin Tatroe
  5. us php Title: Programming PHP
  6. other php Author: George Schlossnagle
  7. other php Title: Advanced PHP Programming
  8. otherother php Author: David Sklar and Adam Trachtenberg
  9. otherother php Title: PHP Cookbook
  10.  
  11.  
  12. testing SamsFactoryMethod
  13. us php Author: Christian Wenz
  14. us php Title: PHP Phrasebook
  15. other php Author: Rasmus Lerdorf and Kevin Tatroe
  16. other php Title: Programming PHP
  17. otherother php Author: Larry Ullman
  18. otherother php Title: PHP for the World Wide Web
  19.  
  20.  
  21. END TESTING FACTORY METHOD 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