php超小型模版类

来源:互联网 发布:java游戏设计培训班 编辑:程序博客网 时间:2024/05/01 23:06
总结:    $smarty的工作流程:    1:把需要显示的全局变量,赋值,塞到对象内部的属性上,一个数组内    2:编译模版,把{$标签},解析成响应的phpe echo代码    3:引入编译后的Php文件    使用smarty的步骤:    1:smarty是一个类,要使用,需先引入并实例化    2:assign赋值    3:dispaly[编译到输出]    smarty之辦    1:编译模版,浪费时间    2:要把变量再重新赋值到对象属性上,增大开销
include('./mini.class.php');$mini=new mini();$mini->template_dir='./templates';$mini->compile_dir='./compile';$content='mao';$mini->assign('content',$content);$mini->display('03.html');

模版类:

<?php/*模版类的第一步:把标签解析Php输出语句模版文件-》PHP文件*//*为了目录清晰,我们把模版和编译后的结果,放在不同的目录里用2个属性来记录这2个目录*/class mini{    public $template_dir='';//模板文件爱你所在的位置    public $compile_dir='';//木板编译后存放的位置    /*        string $template模版名        作用:调用compile来编译模版,并自动引入    */    //定义一个数组,用来接收外部的变量    public $_tpl_var=array();    public function assign($key,$value)    {        $this->_tpl_var[$key]=$value;    }    public function display($template)    {        $comp=$this->compile($template);        include($comp);    }    /*        string $template 模板文件名        return string         流程:把指定的模版内容读过来,再编译成php    */    public function compile($template)    {   //读出模版内容        $temp=$this->template_dir.'/'.$template;        $source=file_get_contents($temp);        $comp=$this->compile_dir.'/'.$template.'.php';        // 判断模版是否已经存在        if(file_exists($comp)&&filemtime($temp)<filemtime($comp))        {            return $comp;        }        //替换模版内容         $source=str_replace('{$','<?php echo $this->_tpl_var[\'', $source);         $source=str_replace('}','\'];?>', $source);        // echo $source;        //再把编译后的内容保存成点Php文件        file_put_contents($comp,$source);        return $comp;    }}
0 0
原创粉丝点击