解释器模式

解释器模式

作者:LAMP小白  点击:1754  发布日期:2012-10-06 20:04:00  返回列表
解释器模式用于分析一个实例的关键元素,并且针对每个元素都提供自己的解释或相应的动作
特定的预定义关键字或符号被定义为表示其他事物,模版处理器用于接受到吗,解释每个关键字以引用特定的指令集,并执行这些代码

userCDInterpreter类包含setUser方法,这个方法接受一个user对象并将其存储在内部,除此之外,这个类还有getInterpreted()

首先getInterpretrd()从user对象中的getProfilePage()获取到原始的字符串信息,这些信息类似于我们写在smarty模版中的东西
接着,这个方法会通过正则在字符串信息中查找是否有{cd.XXXX}这种字符,如果有,那么则将这个字符串的XXX部分写入一个数组

然后new userCD类
这个类有与XXX对应的方法

然后又是foreach,比如XXX为title,那么会调用userCD-mio_gt;title($profile),当然这里的$profile传过去没有任何意义,只是证明可以传参而已 - -

于是我们得到了编译好后的字符串

代码如下

mio_lt;?php
    class user
    {
        protected $_username = '';
        public function __construct($username)
        {
            $this-mio_gt;_username = $username;
        }
        public function getProfilePage()
        {
            $profile =  "mio_lt;h2mio_gt;I like Never Again!mio_lt;/h2mio_gt;";
            $profile .= "I Love all of their songs. My favorite CD:mio_lt;br /mio_gt;";
            $profile .= "{{myCD.getTitle}}!!";
            return $profile;
        }
    }
    class userCD
    {
        protected $_user = null;
        public function setUser($user)
        {
            $this-mio_gt;_user = $user;
        }
        public function getTitle()
        {
            //more here
            $title = 'waste of a rib';
            return $title;
        }
    }
    class userCDInterpreter
    {
        protected $_user = null;
        public function setUser($user)
        {
            $this-mio_gt;_user = $user;
        }
        public function getInterpreted()
        {
            $profile = $this-mio_gt;_user-mio_gt;getProfilePage(); //得到user实例中输出文本
            if(preg_match_all('/{myCD.(.*?)}/', $profile, $triggers, PREG_SET_ORDER)){
                $replacements = array();
                foreach($triggers as $trigger)
                    $replacements[] = $trigger[1]; //这个是userCD要执行的方法名
                $replacements = array_unique($replacements);
            $myCD = new userCD();
            $myCD-mio_gt;setUser($this-mio_gt;_user);
            foreach($replacements as $replacement)
                $profile = str_replace("{{myCD.{$replacement}}}", call_user_func(array($myCD, $replacement)), $profile);
            }//用调用userCD-mio_gt;$replacement获得信息 然后替换掉{}里面的东西
            return $profile;
        }
    }
    $userName = 'mio';
    $user = new user($userName); //生成一个user实例
    $interpreter = new userCDInterpreter(); //生成一个解译器实例
    $interpreter-mio_gt;setUser($user);
    echo "mio_lt;h1mio_gt;{$userName}'s profilemio_lt;/h1mio_gt;";
    echo $interpreter-mio_gt;getInterpreted();
?mio_gt;



上一篇:call_user_func() 下一篇:快递查询API
0