勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

CodeIgniter3でファイルキャッシュする方法

   2024/01/18  PHP CodeIgniter

CodeIgniterでファイルキャッシュが楽に導入できた。そこそこ使いそうなので利用方法をメモ。

 

準備

controllers側でドライバーを読み込んでおく。今回はコンストラクタに書いていた。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$this->load->driver('cache', array('adapter' => 'file'));
$this->load->driver('cache', array('adapter' => 'file'));
$this->load->driver('cache', array('adapter' => 'file'));

 

ソース

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//modelsで書いておくのが良さそう。
function testFunction()
{
$id = 'test';
if( $cache = $this->cache->get("cache_{$id}") ){ //キャッシュの取得
return $cache; //キャッシュがある場合はそれを返す
}
foreach( $hoge as $h ){ //色々処理する
$data = $h;
}
$this->cache->save("cache_{$id}", $data, 600); //$dataを600秒キャッシュさせる
return $data;
}
//modelsで書いておくのが良さそう。 function testFunction() { $id = 'test'; if( $cache = $this->cache->get("cache_{$id}") ){ //キャッシュの取得 return $cache; //キャッシュがある場合はそれを返す } foreach( $hoge as $h ){ //色々処理する $data = $h; } $this->cache->save("cache_{$id}", $data, 600); //$dataを600秒キャッシュさせる return $data; }
//modelsで書いておくのが良さそう。
function testFunction()
{
    $id = 'test';
    if( $cache = $this->cache->get("cache_{$id}") ){ //キャッシュの取得
        return $cache; //キャッシュがある場合はそれを返す
    }

    foreach( $hoge as $h ){ //色々処理する
        $data = $h;
    }

    $this->cache->save("cache_{$id}", $data, 600); //$dataを600秒キャッシュさせる
    return $data;
}

 

その他

デフォルトだと「/application/cache/」にキャッシュファイルが生成される。保存場所を変えたい場合は「/application/config/config.php」の以下の値の部分にパスを記述しておく。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$config['cache_path'] = '';
$config['cache_path'] = '';
$config['cache_path'] = '';

 - PHP CodeIgniter

  関連記事

CodeIgniter4で祝日一覧APIにCURLでリクエストし結果をファイルキャッシュする方法

Codeigniter4.4.4で祝日一覧APIにCURLでリクエストしたい。尚 ...

CodeIgniter4&Bootstrap&jQueryで簡易版お問い合わせページの作成

CodeIgniter4.4.4&Bootstrap&jQuer ...

CodeIgniter4でコントローラ実行の前後に指定したイベントを実行する方法

CodeIgniter4で特定の条件の場合は指定したページにリダイレクトさせたい ...

CodeIgniter4でGET / POSTパラメータの受け取りとルーティング設定方法

CodeIgniter4.4.4でページを開いた際にGET / POSTパラメー ...

CodeIgniter3で共通の変数と定数を設定する方法

CodeIgniter3系で共通する配列が入った変数と、定数を設定したかった。以 ...

S