工大学子

php设计模式之解释器模式

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

 

<?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;

 

posted @ 2016-04-16 22:49  飞天小莫  阅读(203)  评论(0编辑  收藏  举报
飞天小莫