模板引擎實(shí)現(xiàn)的原理 訪問(wèn)php文件, php文件會(huì)去加載模板引擎,通過(guò)模板引擎去加載模板然后替換模板里面的變量 然后生成一個(gè)編譯文件 最后將該編譯文件導(dǎo)入 訪問(wèn)的php文件中輸出 第二次訪問(wèn)的時(shí)候 如果 緩存文件存在或者沒(méi)有被改動(dòng)則直接 導(dǎo)入緩存文件 輸出 否則重新編譯 自定義的一個(gè)模板引擎 mytpl.class.php <?php class mytpl{ //指定模板目錄 private $template_dir; //編譯后的目錄 private $compile_dir; //讀取模板中所有變量的數(shù)組 private $arr_var=array();
//構(gòu)造方法 public function __construct($template_dir="./templates",$compile_dir="./templates_c") { $this->template_dir=rtrim($template_dir,"/")."/"; $this->compile_dir=rtrim($compile_dir,"/")."/"; } //模板中變量分配調(diào)用的方法 public function assign($tpl_var,$value=null){ $this->arr_var[$tpl_var]=$value; } //調(diào)用模板顯示 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);//將替換后的文件寫(xiě)入定義的緩存文件中 }
//包含編譯后的文件 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 //導(dǎo)入模板引擎類 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"); ?> |
|