本文实例讲述了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让我们放在thinkphpextendbehavior中)
在thinkphpextendbehavior中添加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(这个放在thinkphpextenddrivertemplate目录下面)
只是将系统默认的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");
}
更多关于thinkphp相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《codeigniter入门教程》、《ci(codeigniter)框架进阶教程》、《zend framework框架入门教程》及《php模板技术总结》。
希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。
【说明】:
本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!