Smarty配置緩存時間

2018-12-09 11:25 更新

配置緩存時間

緩存可以通過設置 $caching為:Smarty::CACHING_LIFETIME_CURRENT 或Smarty::CACHING_LIFETIME_SAVED來開啟。

Example 15.1. 開啟緩存

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

// 使用$smarty->cacheLifetime()可以更精確定義緩存時間

$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);

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

開啟了緩存,調(diào)用display('index.tpl') 會正常渲染模板,但也會保存一份輸出的內(nèi)容到$cache_dir目錄下的文件中(緩存副本)。 在下一次調(diào)用display('index.tpl'), 緩存文件會替代渲染模板的過程。

技術(shù)說明

$cache_dir下的文件,文件名與模板名稱相似。 雖然這些文件也有.php后綴,但它們不會被直接執(zhí)行。請不要編輯這些文件!

每個緩存頁面都有一個緩存過期時間$cache_lifetime。 默認是3600秒,也就是一小時。 當超過了此時間,緩存將被重新生成。 當設置$cachingSmarty::CACHING_LIFETIME_SAVED時,可以給每個緩存設置其單獨的緩存時間。 參見$cache_lifetime

Example 15.2. 為每個緩存設置$cache_lifetime

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

// 讓每個緩存的過期時間都可以在display執(zhí)行前單獨設置。
$smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED);

// 設置index.tpl的過期時間為5分鐘
$smarty->setCacheLifetime(300);
$smarty->display('index.tpl');

// 設置home.tpl的過期時間為1小時
$smarty->setCacheLifetime(3600);
$smarty->display('home.tpl');

// 注意:當$caching設置了Smarty::CACHING_LIFETIME_SAVED后,
// 下面的$cache_lifetime將不會起效。
// home.tpl已經(jīng)設置了過期時間為1小時,
// 所以不會再遵循下面的$cache_lifetime值,
// home.tpl的過期時間還是1小時。
$smarty->setCacheLifetime(30); // 30 秒
$smarty->display('home.tpl');
?>

當 $compile_check開啟的時候(默認開啟), 每個模板文件和配置文件都會在緩存檢查的時候執(zhí)行編譯檢查。 如果這些文件在緩存生成后被修改,那么緩存會馬上重新生成。 這是一個覆蓋的選項,所以更好的性能建議把 $compile_check 設置成false。

Example 15.3. 關(guān)閉 $compile_check

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

$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
$smarty->setCompileCheck(false);

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

如果開啟了 $force_compile, 緩存文件將總是會重新生成。效果和關(guān)閉緩存是一樣的, 而且還會降低性能。 $force_compile 一般用于 調(diào)試的目的。 更確當?shù)姆绞绞前丫彺?em>$caching設置成Smarty::CACHING_OFF。

isCached() 函數(shù)可以檢查模板的緩存是否存在。 如果你的模板是需要讀取某些數(shù)據(jù)(如數(shù)據(jù)庫), 那么你可以用它來跳過這個過程。

Example 15.4. 使用 isCached()

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

$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);

if(!$smarty->isCached('index.tpl')) {
	// 找不到緩存,這里進行一些賦值操作
    $contents = get_database_contents();
    $smarty->assign($contents);
}

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

你可以使用{nocache}{/nocache}來設置頁面上部分區(qū)塊是動態(tài)的(不緩存), 同樣你也可以使用 {insert}函數(shù),或者nocache參數(shù)來達到同樣目的。

比如說我們希望把整個頁面緩存,除了頁面兩邊顯示的banner廣告。 那么我們可以用{insert}來顯示banner廣告, 這樣就可以在緩存的內(nèi)容里面,保存廣告部分的動態(tài)效果。 參見 {insert}的詳細文檔。

你可以通過clearAllCache()來刪除全部緩存,或者 用clearCache() 來刪除特定的緩存組的緩存內(nèi)容。

Example 15.5. 刪除緩存

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

$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);

// 僅刪除index.tpl的緩存
$smarty->clearCache('index.tpl');

// 刪除全部緩存
$smarty->clearAllCache();

$smarty->display('index.tpl');
?>
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號