Smarty实现原理分析

现在我们来做个建议的模版引擎

先建一个MySmarty类

<?php
class MySmarty{
    public $config  =    array(
            'template_dir'  =>'./template',
            'compile_dir'   =>'./compile',  
    );
    public $arr = array();//
          
    public function __construct()
    {
        //这里可以定义一个配置类然后导入,这里就不做了
    }
          
        //传参方法
    public function assign($content,$replacment=null)
    {
                //以键值对的形式
        if($content!=null)
        {
            $this->arr[$content] = $replacment;
        }
    }
          
        //显示方法
    public function display($tp)
    {
        $tempfile = $this->config['template_dir']."/".$tp.".html";
        if(!file_exists($tempfile))
        {
            exit("没有模版");
        }
              
        $newfile = $this->config['compile_dir']."/com_".md5($tp).".php";
              
        $tplContent=$this->con_replace(file_get_contents($tempfile));//将smarty标签替换为php的标签
        file_put_contents($newfile,$tplContent);
        //显示编译后的内容
                include $newfile;
    }
          
    function  con_replace($content)
    {
                //替换<{$data}>的形式的内容,这里外标签可用配置文件代替
        $pattern = array(
                '/<{s*$([a-zA-Z_][a-zA-Z_0-9]*)s*}>/i'
        );
        $replacement = array(
                '<?php echo $this->arr["${1}"] ?>'
        );
        return preg_replace($pattern,$replacement,$content);
    }
          
}
?>


然后是程序代码:

<?php
include "./mysmarty.php";
$title="深入浅出之Smarty模板引擎工作机制";
$content="Smarty模板引擎工作机制流程图";
$auth="xwq";
$website="http://xia406413214.web-107.com";
    
    
$tpl= new MySmarty();
$tpl->assign("title",$title);
$tpl->assign("content",$content);
$tpl->assign("auth",$auth);
$tpl->assign("website",$website);
    
$tpl->display("cs");
    
?>


最后定制模版就可以了

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><{$title}></title>
</head>
<body>
<p>内容:<{$content}></p>
<p>作者:<{$auth}></p>
<p>网址:<{$website}></p>
</body>
</html>



OK简单的模版引擎就好了,接下来我会慢慢完善代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值