在调用display()或者
fetch()的时候,
你可以设置单个页面有多个缓存。
当我们希望执行display('index.tpl')的时候,
可以根据不同的情况来生成不同的缓存,并且可以单独区分,
那么就需要设置$cache_id为第二个参数来实现了。
Example 15.6. display()的参数作为$cache_id
<?php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
$my_cache_id = $_GET['article_id'];
$smarty->display('index.tpl', $my_cache_id);
?>
上面,我们将$my_cache_id值作为$cache_id参数传递给
display()。
每个单独的$my_cache_id值,对应将会有单独的
index.tpl模板的缓存文件生成。
在这个例子里面,$cache_id是我们从URL中获得的article_id。
技术说明
当客户端(浏览器)传递值到Smarty或任何的PHP程序时,务必谨慎。
虽然上面例子通过URL传递article_id显得比较方便,但可能会引起问题。
$cache_id值会用来建立文件目录的,
所以如果用户故意传递了非常大的值给article_id,或写个快速循环的脚本来发送随机的article_id,
那么这很有可能引起一些服务器端的问题。
要记住,使用任何数据前要先检查。
在上面的例子中,或许article_id有10个字符的长度,
仅可以是字母数组的组合,而且还应该是存在于数据库内,那么,你就应该检查它!
确保用同一个$cache_id作为
isCached() 和
clearCache()的第二个参数。
Example 15.7. 给 isCached() 传递一个 cache_id
<?php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
$my_cache_id = $_GET['article_id'];
if(!$smarty->isCached('index.tpl',$my_cache_id)) {
// 没有缓存,这里将进行一些赋值操作
$contents = get_database_contents();
$smarty->assign($contents);
}
$smarty->display('index.tpl',$my_cache_id);
?>
要删除特定$cache_id的全部缓存,
同时需要给clearCache()
传递null作为第一个参数。
Example 15.8. 删除特定$cache_id的缓存
<?php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
// 删除$cache_id为"sports"的全部缓存
$smarty->clearCache(null,'sports');
$smarty->display('index.tpl','sports');
?>
按这种方式,你可以通过设置同一个$cache_id来把你的缓存“组织”起来。
