shubraVeil/includes/Cache.php

77 lines
1.8 KiB
PHP
Raw Normal View History

2024-12-25 13:05:50 +02:00
<?php
class Cache {
private static $instance = null;
private $cache_path;
private $duration;
private function __construct() {
$this->cache_path = CACHE_PATH;
$this->duration = CACHE_DURATION;
if (!file_exists($this->cache_path)) {
mkdir($this->cache_path, 0755, true);
}
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function set($key, $data) {
if (!CACHE_ENABLED) return false;
$cache_file = $this->getCacheFile($key);
$cache_data = [
'expires' => time() + $this->duration,
'data' => $data
];
return file_put_contents($cache_file, serialize($cache_data)) !== false;
}
public function get($key) {
if (!CACHE_ENABLED) return false;
$cache_file = $this->getCacheFile($key);
if (!file_exists($cache_file)) {
return false;
}
$cache_data = unserialize(file_get_contents($cache_file));
if ($cache_data['expires'] < time()) {
unlink($cache_file);
return false;
}
return $cache_data['data'];
}
public function delete($key) {
$cache_file = $this->getCacheFile($key);
if (file_exists($cache_file)) {
return unlink($cache_file);
}
return true;
}
public function clear() {
$files = glob($this->cache_path . '/*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
return true;
}
private function getCacheFile($key) {
return $this->cache_path . '/' . md5($key) . '.cache';
}
}