FuelPHP CacheドライバにRedisを使用する
FuelPHPのキャッシュCache クラス
Redisドライバを使用して、Cache クラスを利用してみます。
設定
fuel/app/config/development/に「cache.php」を新規作成します。
内容は以下のとおり。
・fuel/app/config/development/cache.php
- <?php
- return array(
- // default storage driver
- 'driver' => 'redis',
- // default expiration (null = no expiration)
- 'expiration' => null,
- // specific configuration settings for the redis driver
- 'redis' => array(
- 'database' => 'default', // name of the redis database to use (as configured in config/db.php)
- ),
- );
driverに「redis」を指定し、設定は「default」を利用するよう指定しました。
続いて、fuel/app/config/development/db.phpを編集します。
・fuel/app/config/development/db.php
- <?php
- /**
- * The development database settings. These get merged with the global settings.
- */
- return array(
- 'default' => array(
- 'connection' => array(
- 'dsn' => 'mysql:host=localhost;dbname=fuel_dev',
- 'username' => 'root',
- 'password' => 'root',
- ),
- ),
- // --- 以下を追記
- 'redis' => array(
- 'default' => array(
- 'hostname' => '127.0.0.1',
- 'port' => 6379,
- 'timeout' => null,
- 'database' => 0,
- ),
- ),
- );
Redisに接続するための設定を記載します。
これで設定ファイルの準備は完了です。
サンプルプログラム
fuel/app/classes/controller/test.phpを作成。
適当なサンプルを記載します。
- <?php
- class Controller_Test extends Controller
- {
- public function action_index()
- {
- $counter = 0;
- try {
- $counter = Cache::get('counter');
- } catch (\CacheNotFoundException $e) {
- // 初回、キーが存在しない場合はエラーになる
- }
- echo $counter;
- Cache::set('counter', $counter + 1);
- }
- }
これで、http://[サーバーIP]/testに接続するたび、
カウントが上昇するはずです。


