smarty缓存设置及局部缓存
2011-04-26 10:57
357 查看
smarty缓存设置及局部缓存
2008-07-25 17:06
2008-07-25 17:06
最近在项目中用了smarty缓存,对smarty缓存机制有了新的认识。 smarty缓存配置 $smarty->cache_dir = "/caches/";//缓存目录 $smarty->caching = true;//开启缓存,为flase的时侯缓存无效 $smarty->cache_lifetime = 60;//缓存时间 使用 if(!$smarty->is_cached("模板文件")) { //数据库查询 } 如果是分页缓存,单个模板多个缓存 if(!$smarty->is_cached("模板文件","页码")) { //数据库查询 } $smarty->display("模板文件","页码"); 局部缓存: 一、使用insert函数使模板的一部分不被缓存 index.tpl: <div>{insert name="get_current_time"}</div> index.php function insert_get_current_time(){ return date("Y-m-d H:m:s"); } $smarty=new smarty(); $smarty->caching = true; if(!$smarty->is_cached()){ ....... } $smarty->display('index.tpl'); 注解: 定义一个函数,函数名格式为:inser_name(array $params, object &$smarty), 函数参数可选的,如果在模板的insert方法中需要加入其他属性,就会作为数组传递给用户定义的函数。 如:{insert name='get_current_time' local='zh'} 在get_current_time函数中我们就可以通过$params['local']来获得属性值。 如果在get_current_time函数中需要用到当前smarty对象的方法或属性,就可以通过第二个参数获得。 这时你会发现index.tpl已被缓存,但当前时间却随每次刷新在不断变化。 inset 函数默认是不缓存的。并且这个属性不能修改。从这个意义上讲insert函数对缓存的控制能力似乎不如register_function和register_block强 二、用插件改造方法,将该功能改成一个插件: 1)定义一件插件函数:block.cacheless.php,放在smarty的plugins目录 block.cacheless.php的内容如下: <?php function smarty_block_cacheless($param, $content, &$smarty) { return $content; } ?> 2) 编写程序及模板 示例程序:testCacheLess.php <?php include('Smarty.class.php'); $smarty = new Smarty; $smarty->caching=true; $smarty->cache_lifetime = 6; $smarty->display('cache.tpl'); ?> 所用的模板:cache.tpl <?php 已经缓存的:{$smarty.now}<br> {cacheless} 没有缓存的:{$smarty.now} {/cacheless} ?> 现在运行一下,发现是不起作用的,两行内容都被缓存了 3)改写Smarty_Compiler.class.php(注:该文件很重要,请先备份,以在必要时恢复) 查找: $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true); //我的在705行 修改成: if($tag_command == 'cacheless') $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, false); else $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true); 你也可以直接将原句的最后一个参数改成false,我对smarty的内部机制不太了解,所以加了一个判断,只要block是cacheless的才不作缓存 4)OK,现在清除template_c里的编译文件,重新运行,起作用了吧? 经过这些改造,以后只需要在模板定义中,不需要缓存的部分(实时比分,广告,时间等)使用{cacheless}不需缓存的内容{/cacheless}即可 |
相关文章推荐
- smarty3缓存设置
- Smarty之缓存,局部缓存
- smarty局部缓存,报错 Notice: Undefined index: data Notice: Trying to get property of non-object
- PHP Smarty 文件缓存,局部不缓存
- smarty的局部缓存
- smarty 局部不缓存
- smarty局部缓存
- smarty自定义实现局部不缓存
- Smarty中局部不缓存
- smarty局部缓存
- php学习笔记(三十九)smarty缓存特性的使用(包括局部缓存)
- SMARTY局部缓存
- smarty局部缓存的解决办法
- smarty局部缓存技术
- smarty 实现局部缓存
- smarty局部缓存
- smarty页面局部缓存
- smarty局部缓存
- 设置Smarty中缓存的生存时间
- smarty中的缓存设置