模板引擎我们并不陌生,常见的有Smarty模板引擎,另外我们经常使用的MVC框架中也有用到模板引擎,当然框架中是自己实现的模板引擎,模板引擎的原理大多都是一样的。
即:我们访问php文件的时候,php文件去加载模板引擎,模板引擎再去加载模板,并通过程序替换模板中的变量,并生成一个“编译”文件,然后在访问的php文件中引入这个编译文件来输出。这个类似“缓存”,当再次访问这个文件的时候,如果该编译文件存在且未被改动过,则直接加载,否则重新编译。
下面简单实现一个模板引擎:
文件结构
--templates
----tpl.html
--templates_c
--mytpl.class.php
--testtpl.php
首先,自定义一个模板引擎。
mytpl.class.php
<?php class mytpl{ private $template_dir; private $compile_dir; private $arr_var=array(); public function __construct($template_dir="./templates",$compile_dir="./templates_c") { $this->template_dir = rtrim($template_dir,'/').'/'; $this->compile_dir = rtrim($compile_dir,'/').'/'; } public function assign($tpl_var.$value) { $this->arr_var[$tpl_var] = $value; } public function display($fileName) { $tplFile = $this->template_dir.$fileName; if(!file_exists($tplFile)){ return false; } $comFileName=$this->compile_dir."com_".$fileName.".php"; if(!file_exists($comFileName) || filemtime($comFileName)< filemtime($tplFile)){ $repContent=$this->tmp_replace(file_get_contents($tplFile)); file_put_contents($comFileName,$repContent); } include $comFileName; } private function tmp_replace($content){ $pattern=array( '/\{\s*\$([a-zA-Z_]\w*)\s*\}/i' ); $replacement=array( '<?php echo $this->arr_var["${1}"]; ?>' ); $repContent=preg_replace($pattern,$replacement,$content); return $repContent; } } ?>