LoginSignup
16
25

More than 5 years have passed since last update.

【PHP】 外部apiの実行結果をキャッシュする仕組みを独自に実装

Posted at

例えば

  • Qiitaの記事取得apiを叩いて自分のサイトに表示したい!
  • でもapi叩くのに1秒弱かかるから、24時間くらい結果をキャッシュしたい!
  • キャッシュ用のプラグインとかは入れたくない!

完成品

index.php
<?php 

// file_get_contentsの結果をキャッシュしつつ返す
function getCacheContents($url, $cachePath, $cacheLimit = 86400) {
  if(file_exists($cachePath) && filemtime($cachePath) + $cacheLimit > time()) {
    // キャッシュ有効期間内なのでキャッシュの内容を返す
    return file_get_contents($cachePath);
  } else {
    // キャッシュがないか、期限切れなので取得しなおす
    $data = file_get_contents($url);
    file_put_contents($cachePath, $data, LOCK_EX); // キャッシュに保存
    return $data;
  }
}

説明するまでもないですね!

使い方

index.php
<?php 
// qiitaの記事を取得
function getQiitaItems() {
  $res = getCacheContents('https://qiita.com/api/v2/users/laineus/items?page=1&per_page=20', './cache');
  return json_decode($res);
}
?>

<ul>
  <?php foreach(getQiitaItems() as $val): ?>
  <li><a href="<?= $val->url ?>" target="_blank"><?= $val->title ?></a></li>
  <?php endforeach; ?>
</ul>

動作サンプル

サンプルでは、その取得がキャッシュなのか新規にリクエストしたものかが表示されます。
また、キャッシュ有効期間は10秒になっていますので、何度かリロードしてお試し下さい。

16
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
25