


Implementation method of saving templates to database in TP3.0 framework
This article mainly introduces the method of saving templates to the database in the thinkPHP3.0 framework, and analyzes the specific implementation steps and related operating techniques of saving templates to the database in the process of developing CMS systems using the thinkPHP3.0 framework in the form of examples. Friends who need it can refer to
. The example in this article describes the method of saving templates to the database in the thinkPHP3.0 framework. Share it with everyone for your reference, the details are as follows:
When developing cms, it is used to save the template file into the database and display it on the page
Since thinkphp3.0 is directly from If you read and then parse the template file, you can only develop it yourself for storing the template in the database. There is also a mode function in thinkphp3.0. We can define our own mode to achieve the goal. So how to extend our own What about mode? As follows:
1. Enter
define('MODE_NAME','Ey');
in your entry file. "Ey" is the name of your own extended mode. Please add it to your entry file. Create the Ey folder under the thinkphp/Extend/Mode file
2. Modify
in the Ey directory and add the tags.php file content as follows:
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显示 ), );
The following comments in the file were added manually for my modifications. I just modified the behavior of finding templates and parsing templates in the default tags in thinkphp
Copy the system default action and view classes Go to the directory of Ey (due to parsing the content, you need to modify the action and view classes), modify the fetch method in action.class.php:
protected function fetch($templateFile='',$templateContent='' ){ return $this->view->fetch($templateFile,$templateContent); }
view.class. The modification in the php file is:
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. Expand your own search template class (let’s put our own extended behavior tp in thinkphp\Extend\Behavior)
Add the ExtensionTemplateBehavior.class.php class in thinkphp\Extend\Behavior, the content is as follows:
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. Add a behavior class that parses your own template (this is the same as thinkphp3 .0The default ParseTemplateBehavior.class.php is similar)
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. Add your own class to parse the template content TemplateEy.class.php (this is placed in thinkphp\Extend\Driver \Template directory)
Just modify the system default ThinkTemplate.class.php class and modify the fetch method to modify the code as follows:
##
// 加载模板 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; } }
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"); }
The above is the detailed content of Implementation method of saving templates to database in TP3.0 framework. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



1. Open the Douyin app, find the video you want to download and save, and click the [Share] button in the lower right corner. 2. In the pop-up window that appears, slide the function buttons in the second row to the right, find and click [Save Local]. 3. A new pop-up window will appear at this time, and the user can see the download progress of the video and wait for the download to complete. 4. After the download is completed, there will be a prompt of [Saved, please go to the album to view], so that the video just downloaded will be successfully saved to the user's mobile phone album.

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

PHP is a back-end programming language widely used in website development. It has powerful database operation functions and is often used to interact with databases such as MySQL. However, due to the complexity of Chinese character encoding, problems often arise when dealing with Chinese garbled characters in the database. This article will introduce the skills and practices of PHP in handling Chinese garbled characters in databases, including common causes of garbled characters, solutions and specific code examples. Common reasons for garbled characters are incorrect database character set settings: the correct character set needs to be selected when creating the database, such as utf8 or u
