time(), 'data' => $data ]; // Store in memory cache self::$memoryCache[$key] = $cached; // Store in file cache $filePath = self::getCacheDir() . '/' . $key . '.json'; return @file_put_contents($filePath, json_encode($cached), LOCK_EX) !== false; } /** * Delete cached data * * @param string $prefix Cache prefix * @param mixed $identifier Unique identifier (null to delete all with prefix) * @return bool Success */ public static function delete($prefix, $identifier = null) { if ($identifier !== null) { $key = self::makeKey($prefix, $identifier); unset(self::$memoryCache[$key]); $filePath = self::getCacheDir() . '/' . $key . '.json'; return !file_exists($filePath) || @unlink($filePath); } // Delete all files with this prefix $pattern = self::getCacheDir() . '/' . preg_replace('/[^a-zA-Z0-9_]/', '_', $prefix) . '*.json'; $files = glob($pattern); foreach ($files as $file) { @unlink($file); } // Clear memory cache entries with this prefix foreach (array_keys(self::$memoryCache) as $key) { if (strpos($key, $prefix) === 0) { unset(self::$memoryCache[$key]); } } return true; } /** * Clear all cache * * @return bool Success */ public static function clearAll() { self::$memoryCache = []; $files = glob(self::getCacheDir() . '/*.json'); foreach ($files as $file) { @unlink($file); } return true; } /** * Get data from cache or fetch it using a callback * * @param string $prefix Cache prefix * @param mixed $identifier Unique identifier * @param callable $callback Function to call if cache miss * @param int $ttl Time-to-live in seconds * @return mixed Cached or freshly fetched data */ public static function remember($prefix, $identifier, $callback, $ttl = 300) { $data = self::get($prefix, $identifier, $ttl); if ($data === null) { $data = $callback(); if ($data !== null) { self::set($prefix, $identifier, $data); } } return $data; } /** * Clean up expired cache files (call periodically) * * @param int $maxAge Maximum age in seconds (default 1 hour) */ public static function cleanup($maxAge = 3600) { $files = glob(self::getCacheDir() . '/*.json'); $now = time(); foreach ($files as $file) { if ($now - filemtime($file) > $maxAge) { @unlink($file); } } } }