文件
2026-08-16 17:03:10 +08:00

83 行
2.4 KiB
PHP

<?php
if (!defined('IN_APP')) exit('Forbidden');
class Cache
{
private static $dir;
private static $enabled = true;
const EXT = '.cache';
public static function init($dir, $enabled = true)
{
self::$dir = rtrim($dir, '/\\');
self::$enabled = $enabled;
if (!is_dir(self::$dir)) {
@mkdir(self::$dir, 0755, true);
}
}
public static function put($key, $value, $ttl = 3600)
{
if (!self::$enabled) return false;
$file = self::fileName($key);
$data = [
'expires' => $ttl > 0 ? time() + $ttl : 0,
'created' => time(),
'value' => $value,
];
$content = serialize($data);
return (bool)@file_put_contents($file, $content, LOCK_EX);
}
public static function get($key, $default = null)
{
if (!self::$enabled) return $default;
$file = self::fileName($key);
if (!file_exists($file)) return $default;
$content = @file_get_contents($file);
if ($content === false) return $default;
$data = @unserialize($content);
if (!is_array($data)) {
@unlink($file);
return $default;
}
if ($data['expires'] > 0 && time() > $data['expires']) {
@unlink($file);
return $default;
}
return $data['value'];
}
public static function has($key)
{
return self::get($key, '__NOT_FOUND__') !== '__NOT_FOUND__';
}
public static function forget($key)
{
$file = self::fileName($key);
if (file_exists($file)) {
return @unlink($file);
}
return true;
}
public static function clear()
{
if (!is_dir(self::$dir)) return;
$files = glob(self::$dir . DIRECTORY_SEPARATOR . '*' . self::EXT);
foreach ($files as $f) {
@unlink($f);
}
}
public static function remember($key, $ttl, callable $callback)
{
$value = self::get($key, null);
if ($value !== null) return $value;
$value = $callback();
self::put($key, $value, $ttl);
return $value;
}
public static function getOrSet($key, $ttl, callable $callback)
{
return self::remember($key, $ttl, $callback);
}
private static function fileName($key)
{
return self::$dir . DIRECTORY_SEPARATOR . md5($key) . self::EXT;
}
}