$ttl > 0 ? time() + $ttl : 0, 'created' => time(), 'value' => $value, ]; $content = serialize($data); return (bool)@file_put_contents($file, $content, LOCK_EX); } /** * 读取缓存。过期或不存在返回默认值。 * @param string $key * @param mixed $default 不存在时的默认值 * @return mixed */ 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); } } /** * 带回掉的缓存读取(缓存命中直接返回,未命中执行回调并缓存)。 * @param string $key * @param int $ttl * @param callable $callback 无参回调,返回要缓存的值 * @return mixed */ 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; } /** * 获取或设置(简化版 remember)。 */ public static function getOrSet($key, $ttl, callable $callback) { return self::remember($key, $ttl, $callback); } // ─── 内部 ─── private static function fileName($key) { // 用 md5 确保文件名安全 return self::$dir . DIRECTORY_SEPARATOR . md5($key) . self::EXT; } }