欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP设计模式之解释器模式

程序员文章站 2024-04-05 21:52:07
...
解释器: 解释器设计模式用于分析一个实体的关键元素,并且针对每个元素都提供自己的解释或相应的动作。
解释器设计模式最常用于PHP/HTML 模板系统。
  1. 
  2. class User {
  3. protected $_username = "";
  4. public function __construct($username) {
  5. $this->_username = $username;
  6. }
  7. public function getProfilePage() {
  8. $profile = "

    I like Never Again !

    "
    ;
  9. $profile .= "I love all of their songs. My favorite CD:
    "
    ;
  10. $profile .= "{{myCD.getTitle}}!!";
  11. return $profile;
  12. }
  13. }
  14. class userCD {
  15. public function setUser(User $user) {
  16. $this->_user = $user;
  17. }
  18. public function getTitle() {
  19. $title = "Waste of a Rib";
  20. return $title;
  21. }
  22. }
  23. class userCDInterpreter {
  24. protected $_user = NULL;
  25. public function setUser(User $user) {
  26. $this->_user = $user;
  27. }
  28. public function getInterpreted() {
  29. $profile = $this->_user->getProfilePage();
  30. if (preg_match_all('/\{\{myCD\.(.*?)\}\}/', $profile, $triggers, PREG_SET_ORDER)) {
  31. $replacements = array();
  32. foreach ($triggers as $trigger) {
  33. $replacements[] = $trigger[1];
  34. }
  35. $replacements = array_unique($replacements);
  36. $myCD = new userCD();
  37. $myCD->setUser($this->_user);
  38. foreach ($replacements as $replacement) {
  39. $profile = str_replace("{{myCD.{$replacement}}}", call_user_func(array($myCD, $replacement)), $profile);
  40. }
  41. }
  42. return $profile;
  43. }
  44. }
  45. $username = "aaron";
  46. $user = new User($username);
  47. $interpreter = new userCDInterpreter();
  48. $interpreter->setUser($user);
  49. print "

    {$username}'s Profile

    "
    ;
  50. print $interpreter->getInterpreted();
  51. ?>

数据库脚本请参照:http://www.cxybl.com/html/wlbc/Php/2011_1126_9458.html