相關關鍵詞
關于我們
最新文章
PHP實現(xiàn)簡單的模板引擎功能示例
本文實例講述了PHP實現(xiàn)簡單的模板引擎功能。分享給大家供大家參考,具體如下:
php web開發(fā)中廣泛采取mvc的設計模式,controller傳遞給view層的數(shù)據(jù),必須通過模板引擎才能解析出來。實現(xiàn)一個簡單的僅僅包含if,foreach標簽,解析$foo變量的模板引擎。
編寫template模板類和compiler編譯類。代碼如下:
<?php namespace foo\base; use foo\base\Object; use foo\base\Compiler; /** * */ class Template extends Object { private $_config = [ 'suffix' => '.php',//文件后綴名 'templateDir' => '../views/',//模板所在文件夾 'compileDir' => '../runtime/cache/views/',//編譯后存放的目錄 'suffixCompile' => '.php',//編譯后文件后綴 'isReCacheHtml' => false,//是否需要重新編譯成靜態(tài)html文件 'isSupportPhp' => true,//是否支持php的語法 'cacheTime' => 0,//緩存時間,單位秒 ]; private $_file;//帶編譯模板文件 private $_valueMap = [];//鍵值對 private $_compiler;//編譯器 public function __construct($compiler, $config = []) { $this->_compiler = $compiler; $this->_config = array_merge($this->_config, $config); } /** * [assign 存儲控制器分配的鍵值] * @param [type] $values [鍵值對集合] * @return [type] [description] */ public function assign($values) { if (is_array($values)) { $this->_valueMap = $values; } else { throw new \Exception('控制器分配給視圖的值必須為數(shù)組!'); } return $this; } /** * [show 展現(xiàn)視圖] * @param [type] $file [帶編譯緩存的文件] * @return [type] [description] */ public function show($file) { $this->_file = $file; if (!is_file($this->path())) { throw new \Exception('模板文件'. $file . '不存在!'); } $compileFile = $this->_config['compileDir'] . md5($file) . $this->_config['suffixCompile']; $cacheFile = $this->_config['compileDir'] . md5($file) . '.html'; //編譯后文件不存在或者緩存時間已到期,重新編譯,重新生成html靜態(tài)緩存 if (!is_file($compileFile) || $this->isRecompile($compileFile)) { $this->_compiler->compile($this->path(), $compileFile, $this->_valueMap); $this->_config['isReCacheHtml'] = true; if ($this->isSupportPhp()) { extract($this->_valueMap, EXTR_OVERWRITE);//從數(shù)組中將變量導入到當前的符號表 } } if ($this->isReCacheHtml()) { ob_start(); ob_clean(); include($compileFile); file_put_contents($cacheFile, ob_get_contents()); ob_end_flush(); } else { readfile($cacheFile); } } /** * [isRecompile 根據(jù)緩存時間判斷是否需要重新編譯] * @param [type] $compileFile [編譯后的文件] * @return boolean [description] */ private function isRecompile($compileFile) { return time() - filemtime($compileFile) > $this->_config['cacheTime']; } /** * [isReCacheHtml 是否需要重新緩存靜態(tài)html文件] * @return boolean [description] */ private function isReCacheHtml() { return $this->_config['isReCacheHtml']; } /** * [isSupportPhp 是否支持php語法] * @return boolean [description] */ private function isSupportPhp() { return $this->_config['isSupportPhp']; } /** * [path 獲得模板文件路徑] * @return [type] [description] */ private function path() { return $this->_config['templateDir'] . $this->_file . $this->_config['suffix']; } }