PHP 實現簡單的模板引擎

來源:互聯網
上載者:User
模板引擎作為視圖層和模型曾分離的一種解決方案。

首先我們建立一個Template.class.php 的檔案

 '.m', //設定模板檔案'templateDir' => 'template/', //設定模板所在的檔案夾'compileDir'  => 'cache','debug'      => false,//設定編譯後存放的目錄'cache_htm'  =>  true,//是否需要編譯成靜態html檔案'suffix_cache'=> '.htm',//編譯後的檔案尾碼'cache_time'  =>2000,// 多長時間自動更新'php_turn'    =>false,//是否支援原生的php代碼'cache_control' => 'control.dat',);private $compileTool;//編譯器public $filename;//模板檔案名稱private $value =array();//值棧static private $instance  = null;public $debug = array();//調試資訊public function __construct($arrayConfig =array()){        //返回當前UNIX時間戳記和微妙數$this->debug['begin'] = microtime(true);$this->arrayConfig =$arrayConfig+$this->arrayConfig;$this->getPath();if(!is_dir($this->arrayConfig['templateDir'])){exit("template isnt not found");}if(!is_dir($this->arrayConfig['compileDir'])){mkdir($this->arrayConfig['compileDir'],0770,true);}include("Compile.class.php");//$this->compileTool = new Compile;}/**路徑處理為絕對路徑*/public function getPath(){$this->arrayConfig['templateDir'] = strtr(realpath($this->arrayConfig['templateDir']),'\\','/').'/';$this->arrayConfig['compileDir'] = strtr(realpath($this->arrayConfig['compileDir']),'\\','/').'/';}/***單例模式擷取模板的執行個體**/public static function getInstance(){if(is_null(self::$instance)){self::$instance = new Template();}return self::$instance;}public function setConfig($key,$value = null){if(is_array($key)){$this->arrayConfig = $key+$this->arrayConfig;}else{$this->arrayConfig[$key] = $value;}}public function getConfig($key = null){if($key){return $this->arrayConfig[$key];}else{return $this->arrayConfig;}}/**    注入單個變數**/public function assign($key,$value){$this->value[$key] = $value;}/**    注入多個變數**/public function assignArray($array){if(is_array($array)){foreach($array as $k => $v){$this->value[$k] = $v;}}}/***        擷取模板檔案的路徑**/public function path(){return $this->arrayConfig['templateDir'].$this->filename.$this->arrayConfig['suffix'];}/***是否需要緩衝**/public function needCache(){return $this->arrayConfig['cache_htm'];}/***是否需要重建快取檔案**/public function reCache($file){$flag = false;//產生快取檔案$cacheFile = $this->arrayConfig['compileDir'].md5(@$filename).'.'.'php';//var_dump($cacheFile);if($this->arrayConfig['cache_htm']===true){//設定timeflag (判斷目前時間-模板檔案上次修改的時間)是否小於設定的緩衝時間//如果小於則返回TRUE$timeFlag = (time()-@filemtime($cacheFile))<$this->arrayConfig['cache_time']?true:false;//1,判斷快取檔案是否存在,//2,快取檔案是否有內容//3,時間是否在設定的緩衝時間之內if(!is_file($cacheFile)&&filesize($cacheFile)>1&&$timeFlag){$flag = true;}else{$flag = false;}}return $flag;}/***顯示模板**/public function show($file){$this->filename =$file;if(!is_file($this->path())){exit('找不到相對應的模板');}$compileFile = $this->arrayConfig['compileDir'].'/'.md5(@$filename).'.php';$cacheFile = $this->arrayConfig['compileDir'].md5(@$filename).'.htm';//echo $compileFile;//echo $cacheFile;if($this->reCache($file)===false){$this->debug['cached'] = 'false';//var_dump($compileFile);$this->compileTool = new Compile($this->path(),$compileFile,$this->arrayConfig);if($this->needCache()){//是否需要緩衝ob_start();}//函數從數組中把變數匯入到當前的符號表中extract($this->value,EXTR_OVERWRITE);//判斷 檔案是否存在,組建檔案的修改時間是否小於模板檔案修改時間if(@is_file($compileFile)||filemtime($compileFile)path())){$this->compileTool->vars = $this->value;$this->compileTool->compile();//引入檔案include $compileFile;}else{include $compileFile;}if($this->needCache()){//如果需要緩衝的話$message = ob_get_contents();//則產生快取檔案file_put_contents($cacheFile,$message);}}else{//如果快取檔案時間小於設定的時間//直接讀取快取檔案readfile($cacheFile);//$this->debug['cached'] = true;}$this->debug['spend'] = microtime(true) - $this->debug['begin'];$this->debug['count'] = count($this->value);$this->debug_info();/*var_dump($compileFile);thisvar_dump($this->path());if(!is_file($compileFile)){mkdir($this->arrayConfig['compileDir']);  //此處若存在需要判斷$this->compileTool->compile($this->path(),$compileFile);readfile($compileFile);}else{readfile($compileFile);}*/}/***debug 調試函數**/public function debug_info(){//$this->arrayConfig['debug']=false;if($this->arrayConfig['debug']===true){var_dump($this);echo "程式運行日期",date("Y-m-d h:i:s")."
";echo "模板解析耗時",$this->debug['spend'],'秒'."
";echo "模板包含標籤數目",$this->debug['count']."
";echo "是否使用靜態緩衝",$this->debug['cached']."
";//echo "模板引擎執行個體參數",var_dump($this->getConfig());}}/******清楚緩衝的檔案*****/public function clean($path = null){if($path = null){$path = $this->arrayConfig['CompileDir'];$path = glob($path.'*'.$this->arrayConfig['suffix_cache']);//glob 函數返回匹配指定的檔案夾目錄}else{$path = $this->arrayConfig['compileDir'].md5($path).'.htm';foreach((array)$path as $v){//刪除unlink($v);}}}}

建立一個 Compile.class.php 翻譯模板檔案

template = $template;$this->comfile = $compileFile;$this->content = file_get_contents($template);if($config['php_turn']===false){//echo "123";//$this->T_R[]="";}//echo "123";//正則匹配 {$xxx} 格式$this->T_P[]="#\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}#";$this->T_R[]="value['\\1'];?>";}public function compile(){$this->c_var2();//$this->c_staticFile();//var_dump($this);file_put_contents($this->comfile,$this->content);}public function c_var2(){//        將{$xxx} 替換為$this->content = preg_replace($this->T_P,$this->T_R,$this->content);}public function c_staticFile(){$this->content =preg_replace('#\{\!(.*?)\!\}#','',$this->content);}public function __set($name,$value){$this->$name = $value;}public function __get($name){return $this->$name;}}

建立一個測試檔案 test.php

false,'debug'=>false));$tpl->assign('data','hello world');$tpl->show('member');//var_dump($tpl->getConfig());

模板檔案member.m

welcome

{$data}

顯示

借鑒 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.