码迷,mamicode.com
首页 > Web开发 > 详细

php设计模式之解释器模式

时间:2016-04-17 00:24:12      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

解释器设计模式用于分析一个实体的关键元素,并且针对每个元素都提供自己的解释或相应的动作。

 

<?php
/**
* 解释器模式
*/
class User
{
    protected $_username;

    public function __construct($username)
    {
        $this->_username = $username;
    }

    public function getProfilePage()
    {
        $profile = "<h2>I like never again</h2>";
        $profile .= "I love all of the songs, My favorite CD:<br/>";
        $profile .= "{{myCD.getTitle}}<br/>";
        $profile .= "My name is ";
        $profile .= "{{myCD.getName}}";

        return $profile;
    }
}

/**
*ad
*/
class userCD
{
    protected $_user = NULL;
    public function setUser($user)
    {
        $this->_user = $user;
    }

    public function getTitle()
    {
        return ‘test‘;
    }

    public function getName()
    {
        return ‘111‘;
    }
}

 

 

/**
* interpreter
*/
class userCDInterpreter
{
    protected $_user = NULL;
    function setUser($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);
$echo = $interpreter->getInterpreted();


print "<h1>{$username}‘s Profile</h1>";

print $echo;

 

php设计模式之解释器模式

标签:

原文地址:http://www.cnblogs.com/happig/p/5399707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!