zend framework提供了Zend_Cache::factory,這個factory可以產生出好幾種cache方式,官方範例如下:
// We choose a backend (for example 'File' or 'Sqlite'...) $backendName = '[...]'; // We choose a frontend (for example 'Core', 'Output', 'Page'...) $frontendName = '[...]'; // We set an array of options for the chosen frontend $frontendOptions = array([...]); // We set an array of options for the chosen backend $backendOptions = array([...]); // We create an instance of Zend_Cache // (of course, the two last arguments are optional) $cache = Zend_Cache::factory($frontendName, $backendName, $frontendOptions, $backendOptions);
frontendName:
指的是快取對象,例如資料、頁面、檔案。
backendName:
指的是要儲存的容器,例如存入檔案裡、sqlite、或者是連接至Memcache server等…。
frontendOptions和backendOptions:
指的是可選參數值。
可參考官方frontend cache和backend cache。
在前台頁面中,有一些資料可能是很久才去更新一次,這時就可以使用cache:
- 如果是採用page cache,那可能要只cache一部分頁面,透過ajax抓取,或者直接在view上面加判斷式。
- 透過file cache可直接將抓取到的api資料,直接存入,只要每次去檢查cache時效是否過了,如果時效過則在重新抓取。
以下是一個簡單example:
class FileCache { private $cache; public function FileCache( $lifetime = 300 ){ // 設定 Frontend 選項 $frontendOptions = array( 'lifetime' => $lifetime, // 快取時間 'automatic_serialization' => true, // 自動 serialization ); // 設定 Backend 選項 $backendOptions = array( 'cache_dir' => APPLICATION_PATH . '/cache/', // 快取存放路徑 ); // 建立一個快取物件 $this->cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions); } public function load( $name ){ return $this->cache->load( $name ); } public function save( $name, $data ){ return $this->cache->save( $data, $name ); } public function isAvailable( $name ){ return $this->cache->test( $name ); } }
使用方式如下:
$cache = new FileCache( 60 ); $cacheName = "data_cache"; if( $cache->isAvailabel( $cacheName ) ){ $result = $cache->load( $cacheName ); }else{ $result = array(1,2,3,4,5); $cache->save( $cacheName, $result ) } print_r( $result );