php模板引擎原理

來源:互聯網
上載者:User

標籤:

模板引擎實現的原理

訪問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模板引擎原理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.