模板引擎實現的原理
訪問php文件, php文件會去加載模板引擎,通過模板引擎去加載模板然后替換模板里面的變量 然后生成一個編譯文件
最后將該編譯文件導入 訪問的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=null){
$this->arr_var[$tpl_var]=$value;
}
//調用模板顯示
public function display($fileName){
$tplFile=$this->template_dir.$fileName;
if(!file_exists($tplFile)){
return false;
}
//定義編譯合成的文件 加了前綴 和路徑 和后綴名.php
$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]*)\s*--\>/i'
);
$replacement=array(
'<?php echo $this->arr_var["${1}"]; ?>'
);
$repContent=preg_replace($pattern,$replacement,$content);
return $repContent;
}
}
//使用該模板引擎
<?php
//導入模板引擎類
include"mytpl.class.php";
$title="this is title";
$content="this is content";
$tpl=new mytpl();
//分配變量
$tpl->assign("title",$title);
$tpl->assign("content",$content);
//指定處理的模板
$tpl->display("tpl.html");
?>