Zend_Cache のバックエンド

バックエンドには、標準と拡張の 2 種類があります。 もちろん、拡張バックエンドのほうがより高機能となります。

Zend_Cache_Backend_File

この (拡張) バックエンドは、キャッシュレコードを (指定したディレクトリの) ファイルに保存します。

使用可能なオプションは次のとおりです。

表25 File バックエンドのオプション

オプション データ型 デフォルト値 説明
cache_dir String [system temp dir] キャッシュファイルを書き込むディレクトリ。
file_locking Boolean TRUE ファイルロックを有効/無効にします。 不慮の事故でキャッシュが破壊されることを防げますが、 マルチスレッドなウェブサーバ環境や NFS ファイルシステム上では役に立ちません。
read_control Boolean TRUE 読み込み制御を有効/無効にします。有効にすると キャッシュファイルに制御キーが埋め込まれます。 キャッシュの読み込み後、計算した結果とキャッシュのキーを比較します。
read_control_type String 'crc32' 読み込み制御の方式 (読み込み制御が有効な場合にのみ使用します)。 使用可能な値は 'md5' (一番安全だが、最も遅い)、 'crc32' (安全性には劣るが、より高速。悪くない選択肢です)、 'adler32' (新たな選択肢。crc32 より高速です)、 'strlen' (最も高速。長さのみをチェックします) のいずれかです。
hashed_directory_level Integer 0 ディレクトリ構造のレベルを指定します。0 は "ディレクトリ階層を作らない"、 1 は "一段階のサブディレクトリを作る"、2 は "二段階の……" を意味します。 何千ものキャッシュファイルを使用する場合にのみ、 このオプションによる高速化を実感できるでしょう。 適切な設定値を決めるには、実際にベンチマークを取得するしかありません。 たいていの場合は 1 または 2 でよいでしょう。
hashed_directory_perm Integer 0700 ディレクトリ構造に対する権限を指定します。
file_name_prefix String 'zend_cache' キャッシュファイルのプレフィックスを設定します。 このオプションを設定する際には十分注意しましょう。 あまりにもありふれた値をシステムのキャッシュディレクトリ (/tmp など) で使用すると、 キャッシュの削除の際に余計なものまで削除されてしまうはめになります。
cache_file_umask Integer 0600 キャッシュファイルの umask を設定します。
cache_file_perm Integer 0600 キャッシュファイルに対する権限を指定します。
metatadatas_array_max_size Integer 100 メタデータ配列の内部最大サイズを設定します (よくわからない場合はこの値を変更してはいけません)。

Zend_Cache_Backend_Sqlite

この (拡張) バックエンドは、キャッシュレコードを SQLite データベースに保存します。

使用可能なオプションは次のとおりです。

表26 Sqlite バックエンドのオプション

オプション データ型 デフォルト値 説明
cache_db_complete_path (必須) String NULL SQLite データベースへの (ファイル名も含めた) フルパス。
automatic_vacuum_factor Integer 10 自動バキューム処理の設定を行います。 自動バキューム処理とは、clean()delete() がコールされた際に自動的にデータベースの断片化解消を行う (そしてサイズを縮小する) ことです。 0 を指定すると、自動バキュームを行いません。 1 を指定すると (delete()clean() がコールされると) そのたびにバキュームを行います。 x (1 より大きな整数) を指定すると、 clean()delete() が x 回コールされるたびに 一回の頻度でランダムに自動バキュームを行います。

Zend_Cache_Backend_Memcached

この (拡張) バックエンドは、キャッシュレコードを memcached サーバに保存します。 memcached は、 高性能な分散メモリオブジェクトキャッシュシステムです。このバックエンドを使用するには、 memcached デーモンおよび memcache PECL 拡張モジュール が必要です。

注意: このバックエンドでは、今のところ "タグ" がサポートされていません。 また、引数 "doNotTestCacheValidity=true" もサポートされていません。

使用可能なオプションは次のとおりです。

表27 Memcached バックエンドのオプション

オプション データ型 デフォルト値 説明
servers Array array(array('host' => 'localhost', 'port' => 11211, 'persistent' => true, 'weight' => 1, 'timeout' => 5, 'retry_interval' => 15, 'status' => true, 'failure_callback' => '' )) memcached サーバの配列です。各 memcached サーバの情報は、 以下のような連想配列で指定します。 'host' => (string) : memcached サーバのサーバ名 'port' => (int) : memcached サーバのポート番号 'persistent' => (bool) : この memcached サーバに対して持続的な接続を使用するかどうか 'weight' => (int) : memcached サーバの重み付け 'timeout' => (int) : memcached サーバのタイムアウト 'retry_interval' => (int) : memcached サーバの再試行間隔 'status' => (bool) : memcached サーバのステータス 'failure_callback' => (callback) : memcached サーバのコールバック関数
compression Boolean FALSE その場での圧縮処理を行いたい場合に TRUE を指定します。
compatibility Boolean FALSE 古い memcache サーバ/拡張モジュールとの互換性モードを使用したい場合に TRUE を指定します。

Zend_Cache_Backend_Libmemcached

This (extended) backend stores cache records into a memcached server. memcached is a high-performance, distributed memory object caching system. To use this backend, you need a memcached daemon and the memcached PECL extension.

Be careful : with this backend, "tags" are not supported for the moment as the "doNotTestCacheValidity=true" argument.

Available options are :

表28 Libmemcached Backend Options

Option Data Type Default Value Description
servers Array array(array('host' => 'localhost', 'port' => 11211, 'weight' => 1)) An array of memcached servers ; each memcached server is described by an associative array: 'host' => (string) : the name of the memcached server, 'port' => (int) : the port of the memcached server, 'weight' => (int) :the weight of the memcached server
client Array array( Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT, Memcached::OPT_HASH => Memcached::HASH_MD5, Memcached::OPT_LIBKETAMA_COMPATIBLE => true ) An associative array of memcached client options ; The array key can be the name of the memcached option constant (without 'OPT_') or the integer value of it. See Memcached constants on PHP manual

Zend_Cache_Backend_Apc

この (拡張) バックエンドは、キャッシュレコードを共有メモリに保存する際に APC (Alternative PHP Cache) 拡張モジュールを使用します (当然、このバックエンドを使用するにはこの拡張モジュールが必要です)。

注意: このバックエンドでは、今のところ "タグ" がサポートされていません。 また、引数 "doNotTestCacheValidity=true" もサポートされていません。

このバックエンドではオプションを使用しません。

Zend_Cache_Backend_Xcache

このバックエンドは、キャッシュレコードを共有メモリに保存する際に XCache 拡張モジュールを使用します (当然、このバックエンドを使うにはこの拡張モジュールが必要となります)。

注意: このバックエンドでは、今のところ "タグ" がサポートされていません。 また、引数 "doNotTestCacheValidity=true" もサポートされていません。

使用可能なオプションは次のとおりです。

表29 Xcache バックエンドのオプション

オプション データ型 デフォルト値 説明
user String NULL xcache.admin.user です。 clean() メソッドを使う際に必要です。
password String NULL xcache.admin.pass (MD5 ではない平文形式) です。 clean() メソッドを使う際に必要です。

Zend_Cache_Backend_ZendPlatform

このバックエンドは、Zend Platform 製品のコンテンツキャッシング API を使用します。当然、このバックエンドを使用するには Zend Platform をインストールする必要があります。

このバックエンドはタグをサポートしています。しかし、 クリーニングモード CLEANING_MODE_NOT_MATCHING_TAG はサポートしていません。

Zend_Cache::factory() メソッドでこのバックエンドを指定する場合は、 'Zend' と 'Platform' の間に区切り文字を入れます。区切り文字としては '-'、'.'、' ' あるいは '_' が使用できます。

$cache = Zend_Cache::factory('Core', 'Zend Platform');

このバックエンドではオプションを使用しません。

Zend_Cache_Backend_TwoLevels

この (拡張) バックエンドは複合型です。 キャッシュレコードを、 高速 (だが制限付き) な Apc、Memcache…… および "低速" な File、Sqlite…… の 2 種類の別々のバックエンドに格納します。

このバックエンドは priority パラメータを使用 (フロントエンドレベルで、記録開始時に指定) し、高速バックエンドの残りのスペースを用いてふたつのバックエンドの使用を最適化します。

Zend_Cache::factory() メソッドでこのバックエンドを指定する場合は、 'Two' と 'Levels' の間に区切り文字を入れます。区切り文字としては '-'、'.'、' ' あるいは '_' が使用できます。

$cache = Zend_Cache::factory('Core', 'Two Levels');

使用可能なオプションは次のとおりです。

表30 TwoLevels バックエンドのオプション

オプション データ型 デフォルト値 説明
slow_backend String File "低速" バックエンドの名前。
fast_backend String Apc "高速" バックエンドの名前。
slow_backend_options Array array() "低速" バックエンドのオプション。
fast_backend_options Array array() "高速" バックエンドのオプション。
slow_backend_custom_naming Boolean FALSE TRUE の場合は、引数 slow_backend を完全なクラス名として使用します。 FALSE の場合は、引数をクラス名 "Zend_Cache_Backend_[...]" の最後の部分として使用します。
fast_backend_custom_naming Boolean FALSE TRUE の場合は、引数 fast_backend を完全なクラス名として使用します。 FALSE の場合は、引数をクラス名 "Zend_Cache_Backend_[...]" の最後の部分として使用します。
slow_backend_autoload Boolean FALSE TRUE の場合は、低速バックエンドに対して require_once を行いません (独自のバックエンドを使用する場合にのみ有用です)。
fast_backend_autoload Boolean FALSE TRUE の場合は、高速バックエンドに対して require_once を行いません (独自のバックエンドを使用する場合にのみ有用です)。
auto_refresh_fast_cache Boolean TRUE TRUE の場合は、キャッシュレコードにヒットしたときに 高速キャッシュを自動的にリフレッシュします。
stats_update_factor Integer 10 高速バックエンドを使用率の計算を無効化 / 効率化します (レコードをキャッシュに書き込む際の 高速バックエンド使用率の計算は、 キャッシュ書き込み x 回につき 1 回の割合でランダムに行われます)。

Zend_Cache_Backend_ZendServer_Disk および Zend_Cache_Backend_ZendServer_ShMem

これらのバックエンドは、キャッシュレコードの保存に Zend Server のキャッシュ機能を使用します。

注意: このバックエンドでは、今のところ "タグ" がサポートされていません。 また、引数 "doNotTestCacheValidity=true" もサポートされていません。

これらのバックエンドが動作するのは、Zend Server 環境で HTTP あるいは HTTPS 越しにページをリクエストした場合のみです。 コマンドラインでスクリプトを実行した場合は動作しません。

Zend_Cache::factory() メソッドでこのバックエンドを指定する場合は、 パラメータ customBackendNamingTRUE とします。

$cache = Zend_Cache::factory('Core', 'Zend_Cache_Backend_ZendServer_Disk',
                             $frontendOptions, $backendOptions, false, true);

このバックエンドにはオプションはありません。

Zend_Cache_Backend_Static

This backend works in concert with Zend_Cache_Frontend_Capture (the two must be used together) to save the output from requests as static files. This means the static files are served directly on subsequent requests without any involvement of PHP or the Zend Framework at all.

注記

Zend_Cache_Frontend_Capture operates by registering a callback function to be called when the output buffering it uses is cleaned. In order for this to operate correctly, it must be the final output buffer in the request. To guarantee this, the output buffering used by the Dispatcher must be disabled by calling Zend_Controller_Front's setParam() method, for example, $front->setParam('disableOutputBuffering', true); or adding "resources.frontcontroller.params.disableOutputBuffering = true" to your bootstrap configuration file (assumed INI) if using Zend_Application.

The benefits of this cache include a large throughput increase since all subsequent requests return the static file and don't need any dynamic processing. Of course this also has some disadvantages. The only way to retry the dynamic request is to purge the cached file from elsewhere in the application (or via a cronjob if timed). It is also restricted to single-server applications where only one filesystem is used. Nevertheless, it can be a powerful means of getting more performance without incurring the cost of a proxy on single machines.

Before describing its options, you should note this needs some changes to the default .htaccess file in order for requests to be directed to the static files if they exist. Here's an example of a simple application caching some content, including two specific feeds which need additional treatment to serve a correct Content-Type header:

AddType application/rss+xml .xml
AddType application/atom+xml .xml

RewriteEngine On

RewriteCond %{REQUEST_URI} feed/rss$
RewriteCond %{DOCUMENT_ROOT}/cached/%{REQUEST_URI}.xml -f
RewriteRule .* cached/%{REQUEST_URI}.xml [L,T=application/rss+xml]

RewriteCond %{REQUEST_URI} feed/atom$
RewriteCond %{DOCUMENT_ROOT}/cached/%{REQUEST_URI}.xml -f
RewriteRule .* cached/%{REQUEST_URI}.xml [L,T=application/atom+xml]

RewriteCond %{DOCUMENT_ROOT}/cached/index.html -f
RewriteRule ^/*$ cached/index.html [L]
RewriteCond %{DOCUMENT_ROOT}/cached/%{REQUEST_URI}.(html|xml|json|opml|svg) -f
RewriteRule .* cached/%{REQUEST_URI}.%1 [L]

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^.*$ index.php [NC,L]

The above assumes static files are cached to the directory ./public/cached. We'll cover the option setting this location, "public_dir", below.

Due to the nature of static file caching, the backend class offers two additional methods: remove() and removeRecursively(). Both accept a request URI, which when mapped to the "public_dir" where static files are cached, and has a pre-stored extension appended, provides the name of either a static file to delete, or a directory path to delete recursively. Due to the restraints of Zend_Cache_Backend_Interface, all other methods such as save() accept an ID which is calculated by applying bin2hex() to a request URI.

Given the level at which static caching operates, static file caching is addressed for simpler use with the Zend_Controller_Action_Helper_Cache action helper. This helper assists in setting which actions of a controller to cache, with what tags, and with which extension. It also offers methods for purging the cache by request URI or tag. Static file caching is also assisted by Zend_Cache_Manager which includes pre-configured configuration templates for a static cache (as Zend_Cache_Manager::PAGECACHE or "page"). The defaults therein can be configured as needed to set up a "public_dir" location for caching, etc.

注記

It should be noted that the static cache actually uses a secondary cache to store tags (obviously we can't store them elsewhere since a static cache does not invoke PHP if working correctly). This is just a standard Core cache, and should use a persistent backend such as File or TwoLevels (to take advantage of memory storage without sacrificing permanent persistance). The backend includes the option "tag_cache" to set this up (it is obligatory), or the setInnerCache() method.

表31 Static Backend Options

Option Data Type Default Value Description
public_dir String NULL Directory where to store static files. This must exist in your public directory.
file_locking Boolean TRUE Enable or disable file_locking : Can avoid cache corruption under bad circumstances but it doesn't help on multithread webservers or on NFS filesystems...
read_control Boolean TRUE Enable / disable read control : if enabled, a control key is embedded in the cache file and this key is compared with the one calculated after the reading.
read_control_type String 'crc32' Type of read control (only if read control is enabled). Available values are : 'md5' (best but slowest), 'crc32' (lightly less safe but faster, better choice), 'adler32' (new choice, faster than crc32), 'strlen' for a length only test (fastest).
cache_file_umask Integer 0600 umask for cached files.
cache_directory_umask Integer 0700 Umask for directories created within public_dir.
file_extension String '.html' Default file extension for static files created. This can be configured on the fly, see Zend_Cache_Backend_Static::save() though generally it's recommended to rely on Zend_Controller_Action_Helper_Cache when doing so since it's simpler that way than messing with arrays/serialization manually.
index_filename String 'index' If a request URI does not contain sufficient information to construct a static file (usually this means an index call, e.g. URI of '/'), the index_filename is used instead. So '' or '/' would map to 'index.html' (assuming the default file_extension is '.html').
tag_cache Object NULL Used to set an 'inner' cache utilised to store tags and file extensions associated with static files. This MUST be set or the static cache cannot be tracked and managed.
disable_caching Boolean FALSE If set to TRUE, static files will not be cached. This will force all requests to be dynamic even if marked to be cached in Controllers. Useful for debugging.