スタッフダイアリー

CakePHP HTML Cache Helper

こんにちは。

システム担当島田です。
今回はCakePHPのpluginで提供されているhtml_cacheについて書きたいと思います
※WebサーバーはApache、Cakeのバージョンは1.3系を想定しています。

git
https://github.com/mcurry/html_cache



html_cacheを使うとHtmlCacheHelper::afterLayout()でcacheフォルダにhtmlファイルが作成されます。
mod_rewriteでhtmlファイルがある場合は、そちらを表示して終わるというルールを書くことによって処理の高速化をはかります。

僕の場合次のカスタマイズを行なって使用しています。
・html_cache管理用のコンポーネントの作成
・rewriteルールの追記
・適用アクションのconfig作成

まずはhtml_cache管理用のコンポーネントを作成します。
目的としてはhtml_cacheを使うかの制御を行います。Component::initialize()でController->helpersに値をマージしてます
components以下に作成してください。

html_cache.php


class HtmlCacheComponent extends Object {
  public $_helpers = array (
        'HtmlCache.HtmlCache' => array (
      'www_root' => WWW_ROOT,

    )
  );
  public function initialize(& $Controller, $options = array ()) {
    $this->Controller = $Controller;
    $path = 'html_cache' . '.' . $this->Controller->params['controller'];
    $config = Configure :: read($path);
    if (empty ($config)) {
      return;
    }
    $action = $this->Controller->params['action'];
    if (isset ($config['*']) or (isset ($config[$action]) and $config[$action])) {
      $this->Controller->helpers = Set :: merge($this->Controller->helpers, $this->_helpers);
    }
  }
}
?>


次にrewriteルールを作成します。
細かい制御を行わない場合zipに入っている「webroot.host.htaccess」を参考にすれば大丈夫だと思います。
Controller::a()は適用するがController::b()は適用させたくない場合があったので下記のように書いてます

/products/~は全て適用

  RewriteCond %{REQUEST_URI} ^/products/(.*)$
  RewriteCond %{DOCUMENT_ROOT}/cache/%{REQUEST_URI}/index.html -f
  RewriteRule ^(.*)$ /cache/$1/index.html [L]



/html/~はnewsを除いて適用

  RewriteCond %{REQUEST_URI} ^/html/(.*)$
  RewriteCond %{REQUEST_URI} !^/html/news(.*)$
  RewriteCond %{DOCUMENT_ROOT}/cache/%{REQUEST_URI}/index.html -f
  RewriteRule ^(.*)$ /cache/$1/index.html [L]



最後にconfigを作成します。
今回はConfigureクラスに持たせます。
bootstrap辺りに書くのがいいと思います。


Configure::write('html_cache',array(
  'html'=>array(
    '*'=>true
  ),
  'products'=>array(
    'detail'=>true
  )
));



上記の設定で
htmlコントローラーは全て適用する。
productsコントローラーはdetailアクションのみ適用するという設定になります

はまりやすいポイントとしてcacheフォルダのパーミッションとConfigure::read('debug')が1以上だと動きません。
またquery stringでパラメータを渡しているactionは使わないようにしましょう。