Smarty模板类内部原理实例分析 本文实例讲述了Smarty模板类内部原理。分享给大家供大家参考,具体如下: 之前在学习ThinkPHP的时候,有接触到Smarty模板类,但是一直不知道其内部实现的原理,博主今天终于知道了其内部原理,其实也挺简单的,然后写了一个迷你版的Smarty模板类,对理解其内部原理有了很大的帮助。 1、迷你版Smarty类 首先上代码,最后再进行讲解。 项目结构图 MiniSmarty类代码(MiniSmarty.class.php) tpl_var[$key] = $value; } /** * 编译模板,并引入编译后的文件 * @param str $template 模板文件 * @return void */ public function display($template){ $compile_file = $this->compile($template); include($compile_file); } /** * 将模板文件编译成php文件 * @param str $template 模板文件名 * @return str 编译文件名 */ private function compile($template){ $template_file = $this->template_dir.'/'.$template; //读取模板文件中的内容 $source = file_get_contents($template_file); //判断是否需要再次生产编译文件 $compile_file = $this->compile_dir.'/'.$template.'.php'; //如果存在编译文件且编译文件的修改时间比模板文件大,则不用再次编译,直接返回文件路径 if(file_exists($compile_file) && filemtime($compile_file) > filemtime($template_file)){ return $compile_file; } //解析{$}为tpl_var[\'', $source); $source = str_replace('}', '\'];?>', $source); //生成编译文件 file_put_contents($compile_file, $source); //返回编译后的文件路径 return $compile_file; } } ?> 测试模板类代码(testSmarty.php) template_dir = './template'; $Smarty->compile_dir = './compile'; //2、给模板对象赋值 $title = '两会召开'; $content = '好奶粉,好会议,好新闻'; $Smarty->assign('title',$title); $Smarty->assign('content',$content); //3、显示模板 $template = 'template.html'; $Smarty->display($template); ?> 模板文件(template.html)