thinkPHP3.0架構實現模板儲存到資料庫的方法

來源:互聯網
上載者:User
這篇文章主要介紹了thinkPHP3.0架構實現模板儲存到資料庫的方法,結合執行個體形式分析了使用thinkPHP3.0架構開發CMS系統過程中將模板儲存到資料庫的具體實現步驟與相關操作技巧,需要的朋友可以參考下

本文執行個體講述了thinkPHP3.0架構實現模板儲存到資料庫的方法。分享給大家供大家參考,具體如下:

在開發cms的時候用到如果將模板檔案存入到資料庫並顯示到頁面中

由於thinkphp3.0都是直接從模板檔案中讀取再解析的那麼對於模板存入資料庫中就只有自己開發了,還有thinkphp3.0中有mode的功能我們可以定義自己的mode這樣就可以達到目的了,那麼如何來擴充自己的mode呢?如下:

1.在你的入口檔案中輸入

define('MODE_NAME','Ey');

其中"Ey"就是你自己擴充的mode名稱了,請在你的thinkphp/Extend/Mode檔案下面建立Ey檔案夾

2.在Ey目錄中修改

添加tags.php檔案內容如下:

return array(  'app_init'=>array(  ),  'app_begin'=>array(    'ReadHtmlCache', // 讀取靜態緩衝  ),  'route_check'=>array(    'CheckRoute', // 路由檢測  ),  'app_end'=>array(),  'path_info'=>array(),  'action_begin'=>array(),  'action_end'=>array(),  'view_begin'=>array(),  'view_template'=>array(    'ExtensionTemplate', // 自動定位模板檔案(手動添加)  ),  'view_content'=>array(    'ParseContent'//(手動添加)  ),  'view_filter'=>array(    'ContentReplace', // 模板輸出替換    'TokenBuild',  // 表單令牌    'WriteHtmlCache', // 寫入靜態緩衝    'ShowRuntime', // 已耗用時間顯示  ),  'view_end'=>array(    'ShowPageTrace', // 頁面Trace顯示  ),);

該檔案中後面的注釋中添加手動添加了為我的修改,只是修改thinkphp中預設的tags中尋找模板和解析模板的行為

將系統預設的action和view類複製到Ey的目錄中(由於解析內容,所以要修改action和view類),修改action.class.php中的fetch方法:

protected function fetch($templateFile='',$templateContent='' ){    return $this->view->fetch($templateFile,$templateContent);}

view.class.php檔案中的修改為:

public function fetch($templateFile='',$templateContent = NULL) {    $params['templateFile'] = $templateFile;    $params['cacheFlag'] = true;    if(isset($templateContent)) {      $params['templateContent'] = $templateContent;    }    tag('view_template',$params);    // 頁面緩衝    ob_start();    ob_implicit_flush(0);    if('php' == strtolower(C('TMPL_ENGINE_TYPE'))) { // 使用PHP原生模板      // 模板陣列變數分解成為獨立變數      extract($this->tVar, EXTR_OVERWRITE);      // 直接載入PHP模板      include $templateFile;    }else{      // 視圖解析標籤      $params = array('var'=>$this->tVar,'content'=>$params['templateContent'],'file'=>$params['templateFile'],'cacheFlag'=>$params['cacheFlag']);      tag('view_content',$params);    }    // 擷取並清空緩衝    $content = ob_get_clean();    // 內容過濾標籤    tag('view_filter',$content);    // 輸出模板檔案    return $content;}

3.擴充自己的尋找模板的類(自己擴充的行為tp讓我們放在thinkphp\Extend\Behavior中)
在thinkphp\Extend\Behavior中添加ExtensionTemplateBehavior.class.php類,內容如下:

class ExtensionTemplateBehavior extends Behavior {  // 行為擴充的執行入口必須是run  public function run(&$params){    if( is_array($params) ){      if( array_key_exists('templateFile', $params) ){        $params  = $this->parseTemplateFile($params);      }else{        //異常        throw_exception(L('_TEMPLATE_NOT_EXIST_AND_CONTENT_NULL_').'['.$params['templateFile'].']');      }    }else{      // 自動定位模板檔案      if(!file_exists_case($params))        $params  = $this->parseTemplateFile($params);    }  }  private function parseTemplateFile($params) {    if( is_array($params) ) {      $templateFile = $params['templateFile'];    }else{      $templateFile = $params;    }    if(!isset($params['templateContent'])) { // 是否設定 templateContent 參數      //自動擷取模板檔案      if('' == $templateFile){        // 如果模板檔案名稱為空白 按照預設規則定位        $templateFile = C('TEMPLATE_NAME');      } elseif(false === strpos($templateFile,C('TMPL_TEMPLATE_SUFFIX'))) {        $path  = explode(':',$templateFile);        //如果是外掛程式        if($path[0] == 'Ext') {          $templateFile = str_replace(array('Ext:',$path[1] . ':',$path[2] . ':'),'',$templateFile);          $templateFile = SITE_ROOT . '/Ext/extensions/' . strtolower($path[1]) . '/' . $path[2] . '/Tpl/' . $templateFile . C('TMPL_TEMPLATE_SUFFIX');        } else {          // 解析規則為 模板主題:模組:操作 不支援 跨項目和跨分組調用          $action = array_pop($path);          $module = !empty($path)?array_pop($path):MODULE_NAME;          if(!empty($path)) {// 設定模板主題            $path = dirname(THEME_PATH).'/'.array_pop($path).'/';          }else{            $path = THEME_PATH;          }          $depr = defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/';          $templateFile = $path.$module.$depr.$action.C('TMPL_TEMPLATE_SUFFIX');        }      }    } else {      if('' == $templateFile){        $depr = defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/';        $params['cacheFlag'] = false;      } else {        $path  = explode(':',$templateFile);        //如果是外掛程式        if($path[0] == 'Ext') {          $templateFile = str_replace(array('Ext:',$path[1] . ':',$path[2] . ':'),'',$templateFile);          $templateFile = SITE_ROOT . '/Ext/extensions/' . strtolower($path[1]) . '/' . $path[2] . '/Tpl/' . $templateFile . C('TMPL_TEMPLATE_SUFFIX');        } else {          // 解析規則為 模板主題:模組:操作 不支援 跨項目和跨分組調用          $action = array_pop($path);          $module = !empty($path)?array_pop($path):MODULE_NAME;          if(!empty($path)) {// 設定模板主題            $path = dirname(THEME_PATH).'/'.array_pop($path).'/';          }else{            $path = THEME_PATH;          }          $depr = defined('GROUP_NAME')?C('TMPL_FILE_DEPR'):'/';          $templateFile = $path.$module.$depr.$action.C('TMPL_TEMPLATE_SUFFIX');        }      }    }    if( is_array($params) ){      $params['templateFile'] = $templateFile;      return $params;    }else{      if(!file_exists_case($templateFile))        throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$templateFile.']');      return $templateFile;    }  }}

4.添加解析自己的模板的行為類(這個和thinkphp3.0預設的ParseTemplateBehavior.class.php類似)

class ParseContentBehavior extends Behavior {  protected $options  = array(    // 布局設定    'TMPL_ENGINE_TYPE'   => 'Ey',   // 預設範本引擎 以下設定僅對使用Ey模板引擎有效    'TMPL_CACHFILE_SUFFIX' => '.php',   // 預設範本緩衝尾碼    'TMPL_DENY_FUNC_LIST'  => 'echo,exit', // 模板引擎禁用函數    'TMPL_DENY_PHP' =>false, // 預設範本引擎是否禁用PHP原生代碼    'TMPL_L_DELIM'     => '{',     // 模板引擎普通標籤開始標記    'TMPL_R_DELIM'     => '}',     // 模板引擎普通標籤結束標記    'TMPL_VAR_IDENTIFY'   => 'array',   // 模板變數識別。留空自動判斷,參數為'obj'則表示對象    'TMPL_STRIP_SPACE'   => true,    // 是否去除模板檔案裡面的html空格與換行    'TMPL_CACHE_ON'     => true,    // 是否開啟模板編譯緩衝,設為false則每次都會重新編譯    'TMPL_CACHE_TIME'    =>  0,     // 模板緩衝有效期間 0 為永久,(以數字為值,單位:秒)    'TMPL_LAYOUT_ITEM'  =>  '{__CONTENT__}', // 布局模板的內容替換標識    'LAYOUT_ON'      => false, // 是否啟用布局    'LAYOUT_NAME'    => 'layout', // 當前布局名稱 預設為layout    // Think模板引擎標籤庫相關設定    'TAGLIB_BEGIN'     => '<', // 標籤庫標籤開始標記    'TAGLIB_END'      => '>', // 標籤庫標籤結束標記    'TAGLIB_LOAD'      => true, // 是否使用內建標籤庫之外的其它標籤庫,預設自動檢測    'TAGLIB_BUILD_IN'    => 'cx', // 內建標籤庫名稱(標籤使用不必指定標籤庫名稱),以逗號分隔 注意解析順序    'TAGLIB_PRE_LOAD'    => '',  // 需要額外載入的標籤庫(須指定標籤庫名稱),多個以逗號分隔    );  public function run(&$_data){    $engine = strtolower(C('TMPL_ENGINE_TYPE'));    //這個地方要判斷是否存在檔案    if('think'==$engine){      if($this->checkCache($_data['file'])) { // 緩衝有效        // 分解變數並載入模板緩衝        extract($_data['var'], EXTR_OVERWRITE);        //載入模版快取檔案        include C('CACHE_PATH').md5($_data['file']).C('TMPL_CACHFILE_SUFFIX');      }else{        $tpl = Think::instance('ThinkTemplate');        // 編譯並載入模板檔案        $tpl->fetch($_data['file'],$_data['var']);      }    } else if('ey' == $engine) {      if( !$_data['cacheFlag'] ){        $class  = 'Template'.ucwords($engine);        if(is_file(CORE_PATH.'Driver/Template/'.$class.'.class.php')) {          // 內建驅動          $path = CORE_PATH;        } else {          // 擴充驅動          $path = EXTEND_PATH;        }        if(require_cache($path.'Driver/Template/'.$class.'.class.php')) {          $tpl  = new $class;          $tpl->fetch('',$_data['content'],$_data['var']);        } else { // 類沒有定義          throw_exception(L('_NOT_SUPPERT_').': ' . $class);        }      }else{        //操作        $cache_flag = true;        if(isset($_data['content'])){ //如果指定內容          if ($_data['file']){ //指定緩衝KEY            $_data['file'] = 'custom_' . $_data['file'];          } else { //未指定緩衝KEY,則不緩衝            $cache_flag = false;          }        } else {          if (is_file($_data['file'])){ //如果指定檔案存在            $_data['content'] = file_get_contents($_data['file']);          } else {            throw_exception(L('_TEMPLATE_NOT_EXIST_').'['.$_data['file'].']');          }        }        //這裡檔案和內容一定有一個存在,否則在之前就會有異常了        if($cache_flag && $this->checkCache($_data['file'],$_data['content']) ) { // 緩衝有效          // 分解變數並載入模板緩衝          extract($_data['var'], EXTR_OVERWRITE);          //載入模版快取檔案          include C('CACHE_PATH').md5($_data['file']).C('TMPL_CACHFILE_SUFFIX');        } else {          $class  = 'Template'.ucwords($engine);          if(is_file(CORE_PATH.'Driver/Template/'.$class.'.class.php')) {            // 內建驅動            $path = CORE_PATH;          } else {            // 擴充驅動            $path = EXTEND_PATH;          }          if(require_cache($path.'Driver/Template/'.$class.'.class.php')) {            $tpl  = new $class;            $tpl->fetch($_data['file'],$_data['content'],$_data['var']);          } else { // 類沒有定義            throw_exception(L('_NOT_SUPPERT_').': ' . $class);          }        }      }    } else {      //調用第三方模板引擎解析和輸出      $class  = 'Template'.ucwords($engine);      if(is_file(CORE_PATH.'Driver/Template/'.$class.'.class.php')) {        // 內建驅動        $path = CORE_PATH;      }else{ // 擴充驅動        $path = EXTEND_PATH;      }      if(require_cache($path.'Driver/Template/'.$class.'.class.php')) {        $tpl  = new $class;        $tpl->fetch($_data['file'],$_data['var']);      }else { // 類沒有定義        throw_exception(L('_NOT_SUPPERT_').': ' . $class);      }    }  }  protected function checkCache($tmplTemplateFile = '',$tmplTemplateContent='') {    if (!C('TMPL_CACHE_ON'))// 優先對配置設定檢測      return false;    //快取檔案名    $tmplCacheFile = C('CACHE_PATH').md5($tmplTemplateFile).C('TMPL_CACHFILE_SUFFIX');    if(!is_file($tmplCacheFile)){      return false;    }elseif (filemtime($tmplTemplateFile) > filemtime($tmplCacheFile)) {      // 模板檔案如果有更新則緩衝需要更新      return false;    }elseif (C('TMPL_CACHE_TIME') != 0 && time() > filemtime($tmplCacheFile)+C('TMPL_CACHE_TIME')) {      // 緩衝是否在有效期間      return false;    }    // 開啟布局模板    if(C('LAYOUT_ON')) {      $layoutFile = THEME_PATH.C('LAYOUT_NAME').C('TMPL_TEMPLATE_SUFFIX');      if(filemtime($layoutFile) > filemtime($tmplCacheFile)) {        return false;      }    }    // 緩衝有效    return true;  }}

5.添加自己解析模板內容的類TemplateEy.class.php(這個放在thinkphp\Extend\Driver\Template目錄下面)
只是將系統預設的ThinkTemplate.class.php類修改了fetch方法修改代碼如下:

// 載入模板public function fetch($templateFile,$templateContent,$templateVar) {    $this->tVar = $templateVar;    if($templateContent && !$templateFile) { //不緩衝      if(C('LAYOUT_ON')) {        if(false !== strpos($templateContent,'{__NOLAYOUT__}')) { // 可以單獨定義不使用布局          $templateContent = str_replace('{__NOLAYOUT__}','',$templateContent);        }else{ // 替換布局的主體內容          $layoutFile = THEME_PATH.C('LAYOUT_NAME').$this->config['template_suffix'];          $templateContent = str_replace($this->config['layout_item'],$templateContent,file_get_contents($layoutFile));        }      }      //編譯模板內容      $templateContent = $this->compiler($templateContent);      extract($templateVar, EXTR_OVERWRITE);      echo $templateContent;    } else {      $templateCacheFile = $this->loadTemplate($templateFile,$templateContent);      // 模板陣列變數分解成為獨立變數      extract($templateVar, EXTR_OVERWRITE);      //載入模版快取檔案      include $templateCacheFile;    }}

6.調用如果資料庫中模板的內容不存在那麼我們還是去讀資料庫中的內容:

if( array_key_exists( $display_mode, $params['tpl'] ) && strlen($params['tpl'][$display_mode]) > 0 ){return $this->fetch("Ext:New:Frontend:show",$params['tpl'][$display_mode]);}else{return $this->fetch("Ext:New:Frontend:show");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.