在 Zend Framework 中實作頁面快取,最常見的方式是透過 Zend_Cache::factory() 工廠方法建立快取物件。這個方法接受四個參數:前端類型、後端類型、前端選項與後端選項,靈活配置快取行為。
class Zend_Controller_Shawn extends Zend_Controller_Action {
public static $cache;
public function init() {
// 前端設定:頁面快取策略
$frontendOptions = array(
'lifetime' => 3600, // 快取壽命(秒)
'debug_header' => true, // 開啟除錯標頭,正式環境建議 false
'regexps' => array( // 依 URL 規則決定是否快取
'^/$' => array('cache' => true), // 首頁快取
'^/index/' => array('cache' => true), // index 模組下所有 action 快取
'^/index/search' => array('cache' => false) // search action 不快取
),
'default_options' => array(
'cache_with_get_variables' => true,
'cache_with_post_variables' => true,
'make_id_with_cookie_variables' => true, // 若使用 Session 必須開啟
'cache_with_session_variables' => true, // 若使用 Session 必須開啟
'cache_with_files_variables' => true,
'cache_with_cookie_variables' => true // 若使用 Session 必須開啟
)
);
// 後端設定:檔案儲存路徑(需存在且可寫入)
$backendOptions = array('cache_dir' => 'C:/www/zend/cache/');
// 建立 Page 前端 + File 後端的快取物件
self::$cache = Zend_Cache::factory('Page', 'File', $frontendOptions, $backendOptions);
self::$cache->start(); // 啟動快取
// 如需在其他頁面清除快取,可呼叫:
// Zend_Controller_Shawn::$cache->clean(Zend_Cache::CLEANING_MODE_ALL);
}
}
true,否則不同使用者可能看到彼此的快取頁面。更多細節請參考 Zend 官方手冊,其中詳細說明各前端/後端類型、標籤式清除、快取 ID 生成策略等進階主題。