Zend framework page cache

初始projectt為例,可直接至application.ini配置cache的參數。

;關閉預設buffer
resources.frontController.params.disableOutputBuffering = true

resources.cachemanager.page.frontend.name = Page
;cache存活時間      
resources.cachemanager.page.frontend.options.lifetime = 5
;debug模式,會在header最上方顯示提示
resources.cachemanager.page.frontend.options.debug_header = true
;儲存的容器
resources.cachemanager.page.backend.name = File
;設定存放位置
resources.cachemanager.page.backend.options.cache_dir = APPLICATION_PATH "/cache"

;如果不一定要在自身project底下建立cache的目錄
;可直接導向到/tmp即可,以下的權限修改跟folder建立都可以省略
;/tmp底下檔案,當電腦關閉時,將會自動清除
;resources.cachemanager.page.backend.options.cache_dir = "/tmp"

建立cache folder和修改權限:

cd newproject/application

mkdir cache

sudo chown www-data:www-data cache

在controller init的加入要cache的action:

// 註冊 Cache Action Helper
$this->_helper->addHelper(new Zend_Controller_Action_Helper_Cache());

$this->_helper->cache(array(
  'index', // 指定要快取的 Action
));

以IndexController為例如下:

class IndexController extends Zend_Controller_Action      
{

    public function init()      
    {     
        /* Initialize action controller here */   

        // 註冊 Cache Action Helper                 
        $this->_helper->addHelper(new Zend_Controller_Action_Helper_Cache());

        $this->_helper->cache(array(
            'index', // 指定要快取的 Action
        ));

    }

    public function indexAction()
    {              
        // action body
    }
}

當使用debug mode的時候,就會在頁面上出現"DEBUG HEADER : This is a cached page !"的字樣,表示目前是使用cache。