>  기사  >  백엔드 개발  >  thinkPHP3.0 프레임워크는 데이터베이스에 템플릿을 저장하는 방법을 구현합니다.

thinkPHP3.0 프레임워크는 데이터베이스에 템플릿을 저장하는 방법을 구현합니다.

不言
不言원래의
2018-05-04 13:58:491301검색

이 글에서는 thinkPHP3.0 프레임워크에서 템플릿을 데이터베이스에 저장하는 방법을 주로 소개하며, ThinkPHP3.0 프레임워크를 사용하여 CMS 시스템을 개발하는 과정에서 템플릿을 데이터베이스에 저장하는 구체적인 구현 단계와 관련 운영 기술을 분석합니다. 예제의 형식 필요한 것 친구들이 참고할 수 있습니다

이 글에서는 thinkPHP3.0 프레임워크가 템플릿을 데이터베이스에 저장하는 방법에 대한 예제를 설명합니다. 참고하실 수 있도록 공유해 드리며 자세한 내용은 다음과 같습니다.

cms 개발 시 템플릿 파일을 데이터베이스에 저장하고 페이지에 표시하는데 사용됩니다

thinkphp3.0이 템플릿 파일을 직접 읽어서 파싱하기 때문에 따라서 데이터베이스에 저장되는 템플릿은 스스로 개발할 수 있습니다. thinkphp3.0에도 모드 기능이 있는데, 목적을 달성하기 위해 자체 모드를 정의할 수 있습니다. 다음과 같이

1. 항목 파일에

define('MODE_NAME','Ey');

를 입력합니다. 여기서 "Ey"는 자신의 확장 모드 이름입니다. thinkphp/Extend/Mode 파일 아래에 Ey 폴더를 만드세요. 2. Ey 디렉토리에서

를 수정하고 다음과 같이 tagged.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에서 기본 태그 검색 템플릿을 수정하십시오. 그리고 템플릿을 파싱하는 동작

시스템 기본 액션과 뷰 클래스를 Ey 디렉터리에 복사하고(컨텐츠 파싱으로 인해 액션과 뷰 클래스를 수정해야 함), 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를 thinkphpExtendBehavior에 넣자)

Add thinkphpExtendBehavior.class.php 클래스의 ExtensionTemplateBehavior, 내용은 다음과 같습니다:


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模板引擎标签库相关设定
    &#39;TAGLIB_BEGIN&#39;     => &#39;<&#39;, // 标签库标签开始标记
    &#39;TAGLIB_END&#39;      => &#39;>&#39;, // 标签库标签结束标记
    &#39;TAGLIB_LOAD&#39;      => true, // 是否使用内置标签库之外的其它标签库,默认自动检测
    &#39;TAGLIB_BUILD_IN&#39;    => &#39;cx&#39;, // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序
    &#39;TAGLIB_PRE_LOAD&#39;    => &#39;&#39;,  // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
    );
  public function run(&$_data){
    $engine = strtolower(C(&#39;TMPL_ENGINE_TYPE&#39;));
    //这个地方要判断是否存在文件
    if(&#39;think&#39;==$engine){
      if($this->checkCache($_data[&#39;file&#39;])) { // 缓存有效
        // 分解变量并载入模板缓存
        extract($_data[&#39;var&#39;], EXTR_OVERWRITE);
        //载入模版缓存文件
        include C(&#39;CACHE_PATH&#39;).md5($_data[&#39;file&#39;]).C(&#39;TMPL_CACHFILE_SUFFIX&#39;);
      }else{
        $tpl = Think::instance(&#39;ThinkTemplate&#39;);
        // 编译并加载模板文件
        $tpl->fetch($_data[&#39;file&#39;],$_data[&#39;var&#39;]);
      }
    } else if(&#39;ey&#39; == $engine) {
      if( !$_data[&#39;cacheFlag&#39;] ){
        $class  = &#39;Template&#39;.ucwords($engine);
        if(is_file(CORE_PATH.&#39;Driver/Template/&#39;.$class.&#39;.class.php&#39;)) {
          // 内置驱动
          $path = CORE_PATH;
        } else {
          // 扩展驱动
          $path = EXTEND_PATH;
        }
        if(require_cache($path.&#39;Driver/Template/&#39;.$class.&#39;.class.php&#39;)) {
          $tpl  = new $class;
          $tpl->fetch(&#39;&#39;,$_data[&#39;content&#39;],$_data[&#39;var&#39;]);
        } else { // 类没有定义
          throw_exception(L(&#39;_NOT_SUPPERT_&#39;).&#39;: &#39; . $class);
        }
      }else{
        //操作
        $cache_flag = true;
        if(isset($_data[&#39;content&#39;])){ //如果指定内容
          if ($_data[&#39;file&#39;]){ //指定缓存KEY
            $_data[&#39;file&#39;] = &#39;custom_&#39; . $_data[&#39;file&#39;];
          } else { //未指定缓存KEY,则不缓存
            $cache_flag = false;
          }
        } else {
          if (is_file($_data[&#39;file&#39;])){ //如果指定文件存在
            $_data[&#39;content&#39;] = file_get_contents($_data[&#39;file&#39;]);
          } else {
            throw_exception(L(&#39;_TEMPLATE_NOT_EXIST_&#39;).&#39;[&#39;.$_data[&#39;file&#39;].&#39;]&#39;);
          }
        }
        //这里文件和内容一定有一个存在,否则在之前就会有异常了
        if($cache_flag && $this->checkCache($_data[&#39;file&#39;],$_data[&#39;content&#39;]) ) { // 缓存有效
          // 分解变量并载入模板缓存
          extract($_data[&#39;var&#39;], EXTR_OVERWRITE);
          //载入模版缓存文件
          include C(&#39;CACHE_PATH&#39;).md5($_data[&#39;file&#39;]).C(&#39;TMPL_CACHFILE_SUFFIX&#39;);
        } else {
          $class  = &#39;Template&#39;.ucwords($engine);
          if(is_file(CORE_PATH.&#39;Driver/Template/&#39;.$class.&#39;.class.php&#39;)) {
            // 内置驱动
            $path = CORE_PATH;
          } else {
            // 扩展驱动
            $path = EXTEND_PATH;
          }
          if(require_cache($path.&#39;Driver/Template/&#39;.$class.&#39;.class.php&#39;)) {
            $tpl  = new $class;
            $tpl->fetch($_data[&#39;file&#39;],$_data[&#39;content&#39;],$_data[&#39;var&#39;]);
          } else { // 类没有定义
            throw_exception(L(&#39;_NOT_SUPPERT_&#39;).&#39;: &#39; . $class);
          }
        }
      }
    } else {
      //调用第三方模板引擎解析和输出
      $class  = &#39;Template&#39;.ucwords($engine);
      if(is_file(CORE_PATH.&#39;Driver/Template/&#39;.$class.&#39;.class.php&#39;)) {
        // 内置驱动
        $path = CORE_PATH;
      }else{ // 扩展驱动
        $path = EXTEND_PATH;
      }
      if(require_cache($path.&#39;Driver/Template/&#39;.$class.&#39;.class.php&#39;)) {
        $tpl  = new $class;
        $tpl->fetch($_data[&#39;file&#39;],$_data[&#39;var&#39;]);
      }else { // 类没有定义
        throw_exception(L(&#39;_NOT_SUPPERT_&#39;).&#39;: &#39; . $class);
      }
    }
  }
  protected function checkCache($tmplTemplateFile = &#39;&#39;,$tmplTemplateContent=&#39;&#39;) {
    if (!C(&#39;TMPL_CACHE_ON&#39;))// 优先对配置设定检测
      return false;
    //缓存文件名
    $tmplCacheFile = C(&#39;CACHE_PATH&#39;).md5($tmplTemplateFile).C(&#39;TMPL_CACHFILE_SUFFIX&#39;);
    if(!is_file($tmplCacheFile)){
      return false;
    }elseif (filemtime($tmplTemplateFile) > filemtime($tmplCacheFile)) {
      // 模板文件如果有更新则缓存需要更新
      return false;
    }elseif (C(&#39;TMPL_CACHE_TIME&#39;) != 0 && time() > filemtime($tmplCacheFile)+C(&#39;TMPL_CACHE_TIME&#39;)) {
      // 缓存是否在有效期
      return false;
    }
    // 开启布局模板
    if(C(&#39;LAYOUT_ON&#39;)) {
      $layoutFile = THEME_PATH.C(&#39;LAYOUT_NAME&#39;).C(&#39;TMPL_TEMPLATE_SUFFIX&#39;);
      if(filemtime($layoutFile) > filemtime($tmplCacheFile)) {
        return false;
      }
    }
    // 缓存有效
    return true;
  }
}

5. 템플릿 내용을 직접 구문 분석하는 TemplateEy.class.php 클래스를 추가합니다. (thinkphpExtendDriverTemplate 디렉토리에 위치)

시스템 기본 ThinkTemplate.class.php 클래스를 수정했습니다. 코드는 다음과 같습니다.


// 加载模板
public function fetch($templateFile,$templateContent,$templateVar) {
    $this->tVar = $templateVar;
    if($templateContent && !$templateFile) { //不缓存
      if(C(&#39;LAYOUT_ON&#39;)) {
        if(false !== strpos($templateContent,&#39;{__NOLAYOUT__}&#39;)) { // 可以单独定义不使用布局
          $templateContent = str_replace(&#39;{__NOLAYOUT__}&#39;,&#39;&#39;,$templateContent);
        }else{ // 替换布局的主体内容
          $layoutFile = THEME_PATH.C(&#39;LAYOUT_NAME&#39;).$this->config[&#39;template_suffix&#39;];
          $templateContent = str_replace($this->config[&#39;layout_item&#39;],$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[&#39;tpl&#39;] ) && strlen($params[&#39;tpl&#39;][$display_mode]) > 0 ){
return $this->fetch("Ext:New:Frontend:show",$params[&#39;tpl&#39;][$display_mode]);
}else{
return $this->fetch("Ext:New:Frontend:show");
}

관련 권장 사항:

thinkphp3.2는 컨트롤러 전반에 걸쳐 다른 모듈을 호출하는 방법을 구현합니다.

thinkPHP 템플릿 산술 연산과 관련된 기능의 사용 분석

위 내용은 thinkPHP3.0 프레임워크는 데이터베이스에 템플릿을 저장하는 방법을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.