標籤:php 物件導向 模板引擎類
<?php/*** 模版引擎類*/class Tpl{//緩衝目錄protected $cacheDir = ‘./Cache/‘;//模版目錄protected $tplDir = ‘./Tpl/‘;//儲存變數的成員方法protected $vars = [];//緩衝有效期間protected $cacheLifeTime = 3600;//初始化成員屬性public function __construct($tplDir = null ,$cacheDir = null ,$cacheLifeTime = null){//判斷緩衝目錄是否存在if (isset($tplDir)) {if ($this->_checkDir($tplDir)) {$this->tplDir = rtrim($tplDir,‘/‘) . ‘/‘;}}//判斷模板路徑是否存在 如果不存在要建立,許可權是否可寫 就需要更改許可權if (isset($cacheDir)) {if ($this->_checkDir($cacheDir)) {$this->tplDir = rtrim($cacheDir,‘/‘) . ‘/‘;}}//初始化緩衝時間if (isset($cacheLifeTime)) {$thsi->cacheLifeTime = $cacheLifeTime;}}//目錄的建立以及許可權的處理private function _checkDir($path){//判斷是否存在目錄以及是否是目錄if (!file_exists($path) || !is_dir($path)) { return mkdir($path,0755,true);}//判斷目錄的許可權是否可讀可寫if (!is_readable($path) || !is_writable($path)) {return chmod($path,0755);}return true;}//分配變數 主要的目的是將模板中需要處理的代碼在php中替換做準備public function assign($key,$val){$this->vars[$key] = $val;}//display 顯示模板檔案public function display($file,$isExecute = true ,$uri = null){ //獲得模板路徑(模板目錄路徑+模板檔案) $tplFilePath = $this->tplDir.$file;//判斷檔案是否存在if (!file_exists($tplFilePath)) {exit(‘模板檔案不存在‘);}//獲得編譯檔案路徑(組合一個全新的檔案名稱和路徑)$cacheFile = md5($file.$uri) . ‘.php‘;$cacheFilePath = $this->cacheDir . $cacheFile;//檢測是否編譯過 是否修改過模板檔案 如果變編譯過 而且在有效期間內則不編譯if (!file_exists($cacheFilePath)) {$html = $this->compile($tplFilePath);} else {//如果修改過模版檔案 就需要刪除原來的編譯檔案重新編譯if (filemtime($tplFilePath) > filemtime($cacheFilePath)) {//刪除原來的檔案unlink($cacheFilePath);//重新編譯$html = $this->compile($tplFilePath);}//檔案建立時間+緩衝有效期間 > time() [目前時間], 沒有到期 否則到期$isTimeout = (filemtime($tplFilePath) + $this->cacheLifeTime > time()) ? false : true;if ($isTimeout) {$html = $this->compile($tplFilePath);}}//編譯if (isset($html)) {if (!file_put_contents($cacheFilePath, $html)) {exit(‘編譯檔案寫入失敗‘);}}//執行if ($isExecute) {extract($this->vars);include $cacheFilePath;}}//編譯的方法 將html的php代碼替換成php代碼來執行 並且產生一個緩衝protected function compile($tplFilePath){//將整個檔案讀入一個字串$html = file_get_contents($tplFilePath);//正則替換規則$keys = [‘{if %%}‘ => ‘<?php if(\1): ?>‘, ‘{else}‘ => ‘<?php else : ?>‘, ‘{else if %%}‘ => ‘<?php elseif(\1) : ?>‘, ‘{elseif %%}‘ => ‘<?php elseif(\1) : ?>‘, ‘{/if}‘ => ‘<?php endif;?>‘, ‘{$%%}‘ => ‘<?=$\1;?>‘, ‘{foreach %%}‘ => ‘<?php foreach(\1) :?>‘, ‘{/foreach}‘ => ‘<?php endforeach;?>‘, ‘{for %%}‘ => ‘<?php for(\1):?>‘, ‘{/for}‘ => ‘<?php endfor;?>‘, ‘{while %%}‘ => ‘<?php while(\1):?>‘, ‘{/while}‘ => ‘<?php endwhile;?>‘, ‘{continue}‘ => ‘<?php continue;?>‘, ‘{break}‘ => ‘<?php break;?>‘, ‘{$%% = $%%}‘ => ‘<?php $\1 = $\2;?>‘, ‘{$%%++}‘ => ‘<?php $\1++;?>‘, ‘{$%%--}‘ => ‘<?php $\1--;?>‘, ‘{comment}‘ => ‘<?php /* ‘, ‘{/comment}‘ => ‘ */ ?>‘, ‘{/*}‘ => ‘<?php /* ‘, ‘{*/}‘ => ‘* ?>‘, ‘{section}‘ => ‘<?php ‘, ‘{/section}‘ => ‘?>‘,‘{{%%(%%)}}‘ => ‘<?=\1(\2);?>‘,‘{include %%}‘ => ‘<?php include "\1";?>‘,];//通過遍曆 然後一一替換foreach ($keys as $key => $value) {//正則匹配替換$patten = ‘#‘ . str_replace(‘%%‘, ‘(.+)‘, preg_quote($key,‘#‘)) . ‘#imsU‘;$replace = $value;//包含檔案處理 include處理方式不一樣if (stripos($patten, ‘include‘)) {// 執行一個Regex搜尋並且使用一個回調進行替換$html = preg_replace_callback($patten, array($this,‘parseInclude‘), $html);} else {$html = preg_replace($patten, $replace, $html);}}return $html;}protected function parseInclude($data){$file = str_replace([‘\‘‘,‘"‘],‘‘,$data[1]);$path = $this->parsePath($file);$this->display($file,false);return ‘<?php include "‘ . $path . ‘";?>‘;}//處理檔案名稱 將漢字元號等統一設定為32位的加密檔案名稱protected function parsePath($file){$path = $this->cacheDir . md5($file).‘.php‘;return $path;}//刪除快取檔案(遞迴)public function clearCache(){self::delDir($this->cacheDir);}//遞迴刪除緩衝的檔案public static function delDir($path){$res = opendir($path);while($file = readdir($res)){if ($file == ‘.‘ || $file == ‘..‘) {continue;}$newPath = $path.‘/‘.$file;if (is_dir($newPath)) {self::delDir($newpath);} else {unlink($newPath);}}}}
測試代碼:
$tpl = new Tpl();$tpl->assign(‘hello‘,‘world‘);$tpl->assign(‘chensen‘,‘你好森林麼麼噠‘);$tpl->display(‘index.html‘);
本文出自 “你好我是森林” 部落格,請務必保留此出處http://chensenlin.blog.51cto.com/10559465/1855944
PHP中物件導向中的模板引擎類