现在的位置: 首页 > 综合 > 正文

smarty 缓存控制

2013年09月06日 ⁄ 综合 ⁄ 共 2708字 ⁄ 字号 评论关闭

smarty 提供了强大的缓存功能。但有时我们并不希望整篇文档都被缓存,而是有
选择的缓存某一部分内容或某一部分内容不被缓存。例如你在页面上端使
用一个带有广告条位置的模板,广告条可以包含任何HTML、图象、FLASH 等混合信息. 因
此这里不能使用一个静态的链接,同时我们也不希望该广告条被缓存. 这就需要在 insert 函
数指定,同时需要一个函数取广告条的内容信息。smarty 也提供了这种缓存控制能力。
我们可以使用{insert}使模板的一部分不被缓存
可以使用$smarty->register_function($params,&$smarty)阻止插件从缓存中输出,还可以
使用$smarty->register_block($params,&$smarty)使整篇页面中的某一块不被缓存。
下面我们真对一个简单需求,分别说明这三种控制缓存输出的方法。
需求:被缓存的文档中当前时间不被缓存,随每次刷新而变化。
1、使用insert 函数使模板的一部分不被缓存
index.tpl:
<div>{insert }</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 local='zh'}
在get_current_time 函数中我们就可以通过$params['local']来获得属性值。
如果在get_current_time 函数中需要用到当前smarty 对象的方法或属性,就可以通过第
二个参数获得。
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');
<div>{insert }</div>

这时你会发现index.tpl 已被缓存,但当前时间却随每次刷新在不断变化。

2、使用register_function 阻止插件从缓存中输出
index.tpl:
<div>{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',fal
se);
if(!$smarty->is_cached()){
.......
}
$smarty->display('index.tpl');

注解:
定义一个函数,函数名格式为:smarty_type_name($params, &$smarty),type 为function
,name 为用户自定义标签名称,在这里是{current_time},两个参数是必须的,即使在函数
中没有使用也要写上。两个参数的功能同上。

3、使用register_block 使整篇页面中的某一块不被缓存
index.tpl:
<div align='center'>
Page created: {"0"|date_format:"%D %H:%M:%S"}
{dynamic}
Now is: {"0"|date_format:"%D %H:%M:%S"}
do other stuff ...
{/dynamic}
</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',fal
se);
if(!$smarty->is_cached()){
.......
}
$smarty->display('index.tpl');
<div>{current_time}</div>

注解:
定义一个函数,函数名格式为:smarty_type_name($params, &$smarty),type 为block,
name 为用户自定义标签名称,在这里是{dynamic},两个参数是必须的,即使在函数中没有
使用也要写上。两个参数的功能同上。

4、总结
(1)对缓存的控制能力:
使用register_function 和register_block 能够方便的控制插件输出的缓冲能力,可以通过
第三个参数控制是否缓存,默认是缓存的,需要我们显示设置为false,正如我们试验中的
所做的那样“$smarty->register_function('current_time','smarty_function_current_time',false);”
但insert 函数默认是不缓存的。并且这个属性不能修改。从这个意义上讲insert 函数对
缓存的控制能力似乎不如register_function 和register_block 强。
(2)使用方便性:
但是insert 函数使用非常方便。不用显示注册,只要在当前请求过程中包含这个函数
smarty 就会自动在当前请求的过程中查找指定的函数。
当然register_function 也可以做到不在运行时显示注册。但是那样做的效果跟其他模版
函数一样,统统被缓存,并且不能控制。
如果你使用在运行时显示调用register_function 注册自定义函数,那么一定要在调用
is_cached()方法前完成函数的注册工作。
否则在is_cached()这一步缓存文档将因为找不到注册函数而导致smarty 错误。

抱歉!评论已关闭.