PHP设计模式之解释器模式
程序员文章站
2024-04-05 21:52:07
...
解释器: 解释器设计模式用于分析一个实体的关键元素,并且针对每个元素都提供自己的解释或相应的动作。
解释器设计模式最常用于PHP/HTML 模板系统。
解释器设计模式最常用于PHP/HTML 模板系统。
-
- class User {
- protected $_username = "";
- public function __construct($username) {
- $this->_username = $username;
- }
- public function getProfilePage() {
- $profile = "
I like Never Again !
";- $profile .= "I love all of their songs. My favorite CD:
";- $profile .= "{{myCD.getTitle}}!!";
- return $profile;
- }
- }
- class userCD {
- public function setUser(User $user) {
- $this->_user = $user;
- }
- public function getTitle() {
- $title = "Waste of a Rib";
- return $title;
- }
- }
- class userCDInterpreter {
- protected $_user = NULL;
- public function setUser(User $user) {
- $this->_user = $user;
- }
- public function getInterpreted() {
- $profile = $this->_user->getProfilePage();
- if (preg_match_all('/\{\{myCD\.(.*?)\}\}/', $profile, $triggers, PREG_SET_ORDER)) {
- $replacements = array();
- foreach ($triggers as $trigger) {
- $replacements[] = $trigger[1];
- }
- $replacements = array_unique($replacements);
- $myCD = new userCD();
- $myCD->setUser($this->_user);
- foreach ($replacements as $replacement) {
- $profile = str_replace("{{myCD.{$replacement}}}", call_user_func(array($myCD, $replacement)), $profile);
- }
- }
- return $profile;
- }
- }
- $username = "aaron";
- $user = new User($username);
- $interpreter = new userCDInterpreter();
- $interpreter->setUser($user);
- print "
{$username}'s Profile
";- print $interpreter->getInterpreted();
- ?>
数据库脚本请参照:http://www.cxybl.com/html/wlbc/Php/2011_1126_9458.html
上一篇: 请教如何从字符串中截取数字
下一篇: 向PHP要效率——加速你的代码执行速度