查看文章 |
smarty 缓存
2010-04-28 10:37
一、使用缓存 要开启smarty的缓存,只需将caching设为true,并指定cache_dir即可. 使用cache_lefetime指定缓存生存时间,单位为秒 要对相同页面生成多个不同的缓存,在display或fetch中加入第二参数cache_id,如$smarty->display(\''index.tpl\'',$my_cache_id);此特性可用于对不同的$_GET进行不同的缓存 二、清除缓存 clear_all_cache();//清除所有缓存 clear_cache(\''index.tpl\'');//清除index.tpl的缓存 clear_cache(\''index.tpl\'',cache_id);//清除指定id的缓存 三、使用自定义缓存方式 设置cache_handler_func使用自定义的函数处理缓存 如: $smarty->cache_handler_func = "myCache"; function myCache($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null){ } 该函数的一般是根椐$action来判断缓存当前操作: switch($action){ case "read"://读取缓存内容 case "write"://写入缓存 case "clear"://清空 } 一般使用md5($tpl_file.$cache_id.$compile_id)作为唯一的cache_id 如果需要,可使用gzcompress和gzuncompress来压缩和解压 四、局部关闭缓存 要在某些区域使缓存失效(只对需要的缓存),有几种方法: inser: 定义一个inser标签要使用的处理函数,函数名格式为:insert_xx(array $params, object &$smarty)其中的xx是insert的name,也就是说,如果你定义的函数为insert_abc,则模板中使用方法为{insert name=\''abc\''} 参数通过$params传入 也可以做成insert插件,文件名命名为:insert.xx.php,函数命名为:smarty_insert_aa($params,&$smarty),xx定义同上 register_block: 定义一个block:smarty_block_name($params,$content, &$smarty){return $content;} //name表示区域名 注册block:$smarty->register_block(\''name\'', \''smarty_block_name\'', false); //第三参数false表示该区域不被缓存 模板写法:{name}内容{/name} 写成block插件: 1)定义一件插件函数:block.cacheless.php,放在smarty的plugins目录 block.cacheless.php的内容如下: 2) 编写程序及模板 示例程序:testCacheLess.php 所用的模板:cache.tpl 已经缓存的:{$smarty.now} {cacheless} 没有缓存的:{$smarty.now} {/cacheless} 关于模板中部分不被缓存的解决办法: smarty提供了强大的缓存功能。但有时我们并不希望整篇文档都被缓存,而是有选择的缓存某一部分内容或某一部分内容不被缓存。例如你在页面上端使用一个带有广告条位置的模板,广告条可以包含任何HTML、图象、FLASH等混合信息. 因此这里不能使用一个静态的链接,同时我们也不希望该广告条被缓存. 这就需要在 insert 函数指定,同时需要一个函数取广告条的内容信息。smarty也提供了这种缓存控制能力。 我们可以使用{insert}使模板的一部分不被缓存 可以使用$smarty->register_function($params,&$smarty)阻止插件从缓存中输出, 还可以使用$smarty->register_block($params,&$smarty)使整篇页面中的某一块不被缓存。 下面我们真对一个简单需求,分别说明这三种控制缓存输出的方法。 需求:被缓存的文档中当前时间不被缓存,随每次刷新而变化。 1、使用insert函数使模板的一部分不被缓存 index.tpl: {insert name="get_current_time"} 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已被缓存,但当前时间却随每次刷新在不断变化。 2、使用register_function阻止插件从缓存中输出 index.tpl: {current_time}{/div} index.php: function smarty_function_current_time($params, &$smarty){ return date("Y-m-d H:m:s"); } $smarty=new smarty(); $smarty->caching = true; $smarty->register_function(\''current_time\'',\''smarty_function_current_time\'',false); if(!$smarty->is_cached()){ ....... } $smarty->display(\''index.tpl\''); 注解: 定义一个函数,函数名格式为:smarty_type_name($params, &$smarty) type为function name为用户自定义标签名称,在这里是{current_time} 两个参数是必须的,即使在函数中没有使用也要写上。两个参数的功能同上。 |
最近读者:

