html5中文学习网

您的位置: 首页 > 网络编程 > PHP编程 » 正文

PHP设计模式之解释器模式_PHP教程_编程技术

[ ] 已经帮助:人解决问题

解释器: 解释器设计模式用于分析一个实体的关键元素,并且针对每个元素都提供自己的解释或相应的动作。
解释器设计模式最常用于PHP/HTML 模板系统。rnyHTML5中文学习网 - HTML5先行者学习网

  1. <?php   
  2.     class User {   
  3.         protected $_username = "";   
  4.         public function __construct($username) {   
  5.             $this->_username = $username;   
  6.         }  
  7.         public function getProfilePage() {   
  8.             $profile  = "<h2>I like Never Again ! </h2>";   
  9.             $profile .= "I love all of their songs. My favorite CD: <br />";   
  10.             $profile .= "{{myCD.getTitle}}!!";   
  11.                
  12.             return $profile;   
  13.         }   
  14.     }   
  15.     class userCD {   
  16.         public function setUser(User $user) {   
  17.             $this->_user = $user;   
  18.         }   
  19.         public function getTitle() {   
  20.             $title = "Waste of a Rib";   
  21.             return $title;   
  22.         }   
  23.     }   
  24.     class userCDInterpreter {   
  25.            
  26.         protected $_user = NULL;   
  27.            
  28.         public function setUser(User $user) {   
  29.             $this->_user = $user;   
  30.         }   
  31.            
  32.         public function getInterpreted() {   
  33.             $profile = $this->_user->getProfilePage();   
  34.                
  35.             if (preg_match_all('//{/{myCD/.(.*?)/}/}/'$profile$triggers, PREG_SET_ORDER)) {   
  36.                 $replacements = array();   
  37.                    
  38.                 foreach ($triggers as $trigger) {   
  39.                     $replacements[] = $trigger[1];   
  40.                 }   
  41.                    
  42.                 $replacements = array_unique($replacements);   
  43.                    
  44.                 $myCD = new userCD();   
  45.                 $myCD->setUser($this->_user);   
  46.                    
  47.                 foreach ($replacements as $replacement) {   
  48.                     $profile = str_replace("{{myCD.{$replacement}}}", call_user_func(array($myCD$replacement)), $profile);   
  49.                 }   
  50.             }   
  51.                
  52.             return $profile;   
  53.         }   
  54.            
  55.     }   
  56.     $username = "aaron";   
  57.     $user = new User($username);   
  58.     $interpreter = new userCDInterpreter();   
  59.     $interpreter->setUser($user);   
  60.        
  61.     print "<h1>{$username}'s Profile</h1>";   
  62.     print $interpreter->getInterpreted();   
  63. ?> 

 数据库脚本请参照:http://www.cxybl.com/html/wlbc/Php/2011_1126_9458.htmlrnyHTML5中文学习网 - HTML5先行者学习网

rnyHTML5中文学习网 - HTML5先行者学习网
rnyHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助