class Cache {
private $cacheDir; // 캐시 디렉토리
private $expire; // 캐시 만료 시간(두번째)
$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'; // 캐시 디렉토리
$ 만료 = 3600; // 캐시 유효성 기간 (초)
$ cache = 새 캐시 ($ cachedir, $ expire);
$ content = $ cache-> get ($ key);
if ($ content === null) {
// 데이터베이스 또는 기타 데이터 소스에서 데이터 가져 오기
$ data = getDataFromdb ();
// 캐시 데이터
$ cache-> set ($ key, json_encode ($ data));
$ content = json_encode ($ data);
}
echo $ 컨텐츠;