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來把你的快取集合起來。