This article mainly introduces the thinkPHP3.0 framework to save the template to the database method, combined with the example form analysis of the use of thinkPHP3.0 framework to develop CMS system in the process of saving the template to the database of the specific implementation steps and related operation skills, the need for friends can refer to the next
The example in this paper describes how the thinkPHP3.0 framework implements templates for saving to a database. Share to everyone for your reference, as follows:
When developing a CMS, if you save the template file to the database and display it to the page
Since thinkphp3.0 are read and parsed directly from the template file, the template is stored in the database only by itself, and there is the function of mode in thinkphp3.0 we can define our own mode so that we can achieve the purpose, So how do you expand your mode? As follows:
1. In your portal file, enter
Define (' Mode_name ', ' Ey ');
where "ey" is your own extension of the mode name, please create the Ey folder under your Thinkphp/extend/mode file
2. Modify in the EY directory
Add the contents of the tags.php file as follows:
Return Array ( ' App_init ' =>array ( ), ' App_begin ' =>array ( ' readhtmlcache ',//read static cache ), ' Route_check ' =>array ( ' checkroute ',//route detection ), ' App_end ' =>array (), ' path_info ' = = Array (), ' Action_begin ' =>array (), ' Action_end ' =>array (), ' View_begin ' =>array (), ' View_template ' =>array ( ' extensiontemplate ',//auto-Locate template file (manually added) ), ' View_content ' =>array ( ' parsecontent '//(manually added) , ' View_filter ' =>array ( ' contentreplace ',//template output Replacement ') Tokenbuild ',/// form token ' Writehtmlcache ',//write static cache ' Showruntime ',//Run time display , ' view_end ' = >array ( ' showpagetrace ',//page trace display ),);
Add the comments in the file later to manually add the behavior for my modifications, just modify the default tags in thinkphp to find templates and resolve templates
Copy the system default action and view class to the directory of EY (to modify the action and view classes for parsing the content), modify the Fetch method in action.class.php:
protected function Fetch ($templateFile = ', $templateContent = ') { return $this->view->fetch ($templateFile , $templateContent);}
The changes in the view.class.php file are:
Public function Fetch ($templateFile = ', $templateContent = NULL) { $params [' templatefile '] = $templateFile; $params [' cacheflag '] = true; if (Isset ($templateContent)) { $params [' templatecontent '] = $templateContent; } Tag (' View_template ', $params); Page Cache Ob_start (); Ob_implicit_flush (0); if (' php ' = = Strtolower (C (' Tmpl_engine_type '))) {//Use PHP Native template //template array variable to decompose into independent variable extract ($this->tvar, Extr_overwrite); Load PHP template include $templateFile directly; } else{ //view Resolution tag $params = Array (' var ' = = $this->tvar, ' content ' = ' $params [' TemplateContent '], ' File ' = ' $params [' templatefile '], ' cacheflag ' = ' $params [' Cacheflag ']); Tag (' view_content ', $params); } Gets and empties the cache $content = Ob_get_clean (); Content Filter Tag Tag (' View_filter ', $content); Output template file return $content;}
3. Extend your own class of find templates (self-expanding behavior TP Let's put in Thinkphp\extend\behavior)
Add the ExtensionTemplateBehavior.class.php class in Thinkphp\extend\behavior, as follows:
The execution portal for class Extensiontemplatebehavior extends Behavior {//Behavior extension must be run public function run (& $params) {if (Is_array ($params)) {if (array_key_exists (' TemplateFile ', $params)) {$params = $this->parsetemplatefile ($params); }else{//Abnormal throw_exception (L (' _template_not_exist_and_content_null_ '). ' ['. $params [' templatefile ']. ']; }}else{//auto-Locate template file if (!file_exists_case ($params)) $params = $this->parsetemplatefile ($params); }} Private Function Parsetemplatefile ($params) {if (Is_array ($params)) {$templateFile = $params [' Templatef Ile ']; }else{$templateFile = $params; if (!isset ($params [' TemplateContent '))} {//Whether the TemplateContent parameter is set//Gets the template file automatically if (' = = $templateFile) { If the template file name is empty, follow the default rules to locate $templateFile = C (' template_name '); } elseif (false = = = Strpos ($templateFile, C (' Tmpl_template_suffix '))) {$path = explode (': ', $templateFile); If it is a pluginif ($path [0] = = ' ext ') {$templateFile = Str_replace (' ext: ', $path [1]. ': ', $path [2]. ': '), ', $templateFile); $templateFile = Site_root. '/ext/extensions/'. Strtolower ($path [1]). '/' . $path [2]. '/tpl/'. $templateFile. C (' Tmpl_template_suffix '); } else {//parsing rule is a template topic: module: Operation does not support cross-project and cross-group calls $action = Array_pop ($path); $module =!empty ($path)? Array_pop ($path): module_name; if (!empty ($path)) {//set template subject $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 it is a plug-in 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 {//parsing rule is a template topic: module: Operation does not support cross-project and cross-group calls $action = Array_pop ($path); $module =!empty ($path)? Array_pop ($path): module_name; if (!empty ($path)) {//set template subject $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 its own template (this is similar to thinkphp3.0 default ParseTemplateBehavior.class.php)
Class Parsecontentbehavior extends Behavior {protected $options = Array (//Layout settings ' tmpl_engine_type ' = ' Ey '), Default template engine The following settings are only valid for use with the EY template engine ' tmpl_cachfile_suffix ' = '. php ',//default template cache suffix ' tmpl_deny_func_list ' + ' echo, Exit ',//Template engine disable function ' tmpl_deny_php ' =>false,//default template engine disable PHP native code ' tmpl_l_delim ' = ' {',//Template engine General tab start label Remember ' Tmpl_r_delim ' + '} ',//template engine plain tag end tag ' tmpl_var_identify ' + ' array ',//template variable recognition. Leave blank to automatically judge, the parameter is ' obj ' means the object ' tmpl_strip_space ' = true,//whether to remove the HTML space inside the template file and the newline ' tmpl_cache_on ' = true, Whether to turn on the template compilation cache, set to False will be recompiled every time ' tmpl_cache_time ' + 0,//template cache validity period 0 is permanent, (value in number, Unit: seconds) ' Tmpl_layout_item ' = = ' {__content__} ',//the contents of the layout template replace the identifier ' layout_on ' and false,//whether the layout is enabled ' Layout_name ' + ' layout ',//when Pre-layout Name defaults to layout//think template engine tag library related Settings ' taglib_begin ' = ' < ',//tag library tag start tag ' taglib_end ' = ' > ', Tag library tag end tag ' Taglib_load ' => True,//whether to use a tag library other than the built-in tag library, the default auto-detect ' taglib_build_in ' + ' cx ',////built-in tag library name (label use does not have to specify the tag library name), comma-delimited note parsing order ' TAGLIB_PR E_load ' + ',//tag libraries that require additional loading (specify tag library name), multiple comma-delimited); Public function Run (&$_data) {$engine = Strtolower (C (' Tmpl_engine_type ')); This place to determine if there is a file if (' think ' = = $engine) {if ($this->checkcache ($_data[' file ')}) {//cache valid/decomposition variable and load template cache Extract ($_data[' var '), Extr_overwrite); Load template cache files include C (' Cache_path '). MD5 ($_data[' file '). C (' Tmpl_cachfile_suffix '); }else{$tpl = think::instance (' thinktemplate '); Compile and load the template file $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 ') {//built-in drive $path = Core_path; } else {//extended drive $path = Extend_path; } if (Require_cache ($patH. ' driver/template/'. $class. Class.php ') {$tpl = new $class; $tpl->fetch (' ', $_data[' content '],$_data[' var '); The else {//class does not define Throw_exception (L (' _not_suppert_ '). ': '. $class); }}else{//operation $cache _flag = true; if (isset ($_data[' content '))) {//If the specified content if ($_data[' file ']) {//Specifies the cache key $_data[' file '] = ' custom_ '. $_d ata[' file '; } else {//No cache key is specified, $cache _flag = false is not cached; }} else {if (Is_file ($_data[' file ')}) {//If the specified files exist $_data[' content '] = file_get_contents ($_dat a[' file ']); } else {throw_exception (L (' _template_not_exist_ '). ' ['. $_data[' file ']. '); }}//There must be a file and content here, otherwise there will be an exception before the IF ($cache _flag && $this->checkcache ($_data[' file '],$_data [' content ']) {//cache valid//decomposition variable and load template cache extract ($_data[' var '), Extr_overwrite); Load template cache files 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 ') {//built-in drive $path = Core_path; } else {//extended drive $path = Extend_path; } if (Require_cache ($path. ' driver/template/'. $class. Class.php ') {$tpl = new $class; $tpl->fetch ($_data[' file '],$_data[' content '],$_data[' var ']); The else {//class does not define Throw_exception (L (' _not_suppert_ '). ': '. $class); }}}} else {//Call third-party template engine parsing and output $class = ' template '. Ucwords ($engine); if (Is_file (core_path. ' driver/template/'. $class. Class.php ') {//built-in drive $path = Core_path; }else{//Extended drive $path = Extend_path; } if (Require_cache ($path. ' driver/template/'. $class. Class.php ') {$tpl = new $class; $tpl->fetch ($_data[' file '],$_dAta[' var '); }else {//class does not define Throw_exception (L (' _not_suppert_ '). ': '. $class); }}} protected function Checkcache ($tmplTemplateFile = ', $tmplTemplateContent = ') {if (! C (' tmpl_cache_on '))//priority to the configuration settings to detect return false; Cache file Name $tmplCacheFile = C (' Cache_path '). MD5 ($tmplTemplateFile). C (' Tmpl_cachfile_suffix '); if (!is_file ($tmplCacheFile)) {return false; }elseif (Filemtime ($tmplTemplateFile) > Filemtime ($tmplCacheFile)) {//template file If there is an update, the cache needs to update return false; }elseif (C (' tmpl_cache_time ')! = 0 && time () > Filemtime ($tmplCacheFile) +c (' Tmpl_cache_time ')) {//cache is The validity period return false; }//Open the Layout template if (C (' layout_on ')) {$layoutFile = Theme_path. C (' Layout_name '). C (' Tmpl_template_suffix '); if (Filemtime ($layoutFile) > Filemtime ($tmplCacheFile)) {return false; }}//cache valid return true; }}
5. Add your own class TemplateEy.class.php for parsing template content (this is placed under the Thinkphp\extend\driver\template directory)
Just the system default ThinkTemplate.class.php class modified the Fetch method to modify the code as follows:
Load template Public function fetch ($templateFile, $templateContent, $templateVar) {$this->tvar = $templateVar; if ($templateContent &&! $templateFile) {//Do not cache if (C (' layout_on ')) {if (False!== Strpos ($templateConte NT, ' {__nolayout__} ')) {//can be individually defined without using layout $templateContent = Str_replace (' {__nolayout__} ', ', $templateContent); }else{//Replace the main content of the layout $layoutFile = Theme_path. C (' Layout_name '). $this->config[' Template_suffix ']; $templateContent = Str_replace ($this->config[' Layout_item '), $templateContent, file_get_contents ($layoutFile)); }}//compile template content $templateContent = $this->compiler ($templateContent); Extract ($templateVar, extr_overwrite); Echo $templateContent; } else {$templateCacheFile = $this->loadtemplate ($templateFile, $templateContent); The template array variable is decomposed into independent variable extract ($templateVar, extr_overwrite); Load template cache file include $templateCacheFile; }}
6. Call if the contents of the template in the database do not exist then we should read the contents of the database:
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");}