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.tw511.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}之間作任何事情,並且保證它將不會像剩下的頁面一樣被快取。