Smarty多個緩存

Multiple Caches Per Page 每頁多個緩存

你可以用單個函數display()或fetch()來輸出多個緩存文檔。display('index.tpl')在多種條件下會有不同的輸出內容,要單獨的把緩存分開。可以通過函數的第二參數cache_id來達到效果。

Example 14-6. passing a cache_id to display()
例14-6.傳給display()一個cache_id

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

$smarty->caching = true;

$my_cache_id = $_GET['article_id'];

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

上面,我們通過變量$my_cache_id作爲cache_id來display()。在index.tpl裏$my_cache_id的每個唯一值,會建立單獨的緩存。在這個例子裏,"article_id"在URL傳送,並用作cache_id。

技術提示:要注意從客戶端(web瀏覽器)傳值到Smarty(或任何PHP應用程序)的過程。儘管上面的例子用article_id從URL傳值看起來很方便,卻可能有糟糕的後果[安全問題]。cache_id被用來在文件系統裏創建目錄,如果用戶想爲article_id賦一個很大的值,或寫一些代碼來快速發送隨機的article_ids,就有可能會使服務器出現問題。確定在使用它之前清空已存在的數據。在這個例子,可能你知道article_id的長度(值吧?!)是10字符,並只由字符-數字組成,在數據庫裏是個可用的article_id。Check for this!要注意檢查這個問題!〔要注意這個提示!不用再說了吧?〕

確定傳給is_cached()和clear_cache()的第二參數是同一個cache_id。

Example 14-7. passing a cache_id to is_cached()
例14-7.傳給is_cached()一個cache_id

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

$smarty->caching = true;

$my_cache_id = $_GET['article_id'];

if(!$smarty->is_cached('index.tpl',$my_cache_id)) {
// No cache available, do variable assignments here.
$contents = get_database_contents();
$smarty->assign($contents);
}

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

你可以通過把clear_cache()的第一參數設爲null來爲特定的cache_id清除所有緩存。

Example 14-8. clearing all caches for a particular cache_id
例14-8.爲特定的cache_id清除所有緩存

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

$smarty->caching = true;

// clear all caches with "sports" as the cache_id
$smarty->clear_cache(null,"sports");

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

通過這種方式,你可以用相同的cache_id來把你的緩存集合起來。