標籤:
模板引擎實現的原理
訪問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");
?>
php模板引擎原理