class Cache {
private $cacheDir; // キャッシュディレクトリ
private $expire; // 有効期限をキャッシュします(2番)
$this->cacheDir = $cacheDir;
$this->expire = $expire;
}
public function get($key) {
$file = md5($key);
$path = $this->cacheDir . '/' . $file;
if (file_exists($path) && time() < filemtime($path) + $this->expire) {
return file_get_contents($path);
}
return null;
}
public function set($key, $content) {
$file = md5($key);
$path = $this->cacheDir . '/' . $file;
file_put_contents($path, $content);
}
public function delete($key) {
$file = md5($key);
$path = $this->cacheDir . '/' . $file;
if (file_exists($path)) {
unlink($path);
}
}
public function clear() {
$files = glob($this->cacheDir . '/*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
}
}
//例を使用します
$ cachedir = '/path/to/cache'; // Cache Directory
$ expire = 3600; //キャッシュ妥当性期間(秒)
$ cache = new Cache($ cachedir、$ expire);
$ content = $ cache-> get($ key);
if($ content === null){
//データベースまたは他のデータソースからデータを取得する
$ data = getDataFromDb();
//データをキャッシュします
$ cache-> set($ key、json_encode($ data));
$ content = json_encode($ data);
}
echo $ content;