一个页面的多个缓存

    对于一次调用display()fetch(),可以存在多个缓存文件。比如说,调用display('index.tpl')时,根据一些条件会有不同的输出内容,而你希望分离这些内容的缓存。要实现这个功能,只要在函数调用时传递$cache_id作为第二个参数即可。

例子14-6. 传递$cache_id给display()

<?php
require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching 1;

$my_cache_id $_GET['article_id'];

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

    在上例中,我们传递变量$my_cache_iddisplay()作为$cache_id。对于每个独立的$my_cache_id值,都会为index.tpl生成独立的缓存。本例中,article_id在URL中传递并被用作$cache_id

技术注解:从客户端(WEB浏览器)向Smarty或PHP应用传递值的时候,要非常小心。在上例中,使用URL中的article_id虽然看起来很方便,但是可能会有不好的后果。$cache_id用来在文件系统中创建一个目录,因此,如果用户传入一个特别大的数值,或者写一个脚本在短时间内快速的发送随机的article_id,有可能会在服务器端造成问题。一定要对传入的数据进行处理然后才使用之。本例中,也许你知道article_id的长度应该是10个字符并只包含数字和字符,并且必须是数据库中存在的一个article_id。请做这些检查!

    调用is_cached()clear_cache()时,请使用相同的$cache_id作为第二个参数。

例子14-7. 传递cache_id给is_cached()

<?php
require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching 1;

$my_cache_id $_GET['article_id'];

if(!
$smarty->is_cached('index.tpl',$my_cache_id)) {
    
// 不存在缓存,进行变量赋值
    
$contents get_database_contents();
    
$smarty->assign($contents);
}

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

    要清除特定$cache_id的所有缓存,可以传递NULL作为第一个参数给clear_cache()

例如14-8. 清除一个特定$cache_id的所有缓存

<?php
require('Smarty.class.php');
$smarty = new Smarty;

$smarty->caching 1;

// 清除所有$cache_id为"sports"的缓存
$smarty->clear_cache(null,'sports');

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

    这样一来,你可以“组合”你的缓存,只要给它们相同的$cache_id即可。