PHP
Cache API Responses with TTL in PHP
Implement a simple file-based caching mechanism for API responses in PHP, reducing redundant requests and improving application performance with a configurable time-to-live.
<?php
/**
* Fetches data from an API, with a caching mechanism.
* Caches responses to a local file with a Time-To-Live (TTL).
*
* @param string $apiUrl The URL of the API endpoint.
* @param int $ttlSeconds Time-to-Live for the cache in seconds.
* @param string $cacheDir Directory to store cache files.
* @return array|null Decoded API response data or null on failure.
*/
function fetchApiWithCache(string $apiUrl, int $ttlSeconds = 3600, string $cacheDir = 'cache/api_cache'): ?array
{
if (!is_dir($cacheDir)) {
mkdir($cacheDir, 0777, true);
}
$cacheKey = md5($apiUrl);
$cacheFile = $cacheDir . '/' . $cacheKey . '.json';
// Check if cache exists and is still valid
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $ttlSeconds)) {
$cachedData = file_get_contents($cacheFile);
if ($cachedData !== false) {
error_log("Serving from cache: " . $apiUrl);
return json_decode($cachedData, true);
}
}
// Cache is expired or doesn't exist, fetch from API
error_log("Fetching from API: " . $apiUrl);
$response = @file_get_contents($apiUrl); // Using @ to suppress warnings for failed fetches
if ($response === false) {
error_log("Failed to fetch data from API: " . $apiUrl);
return null;
}
$data = json_decode($response, true);
if (json_last_error() === JSON_ERROR_NONE) {
// Store valid response in cache
file_put_contents($cacheFile, $response);
return $data;
} else {
error_log("Failed to decode JSON from API: " . $apiUrl . " - " . json_last_error_msg());
return null;
}
}
// Example usage:
// $data = fetchApiWithCache('https://jsonplaceholder.typicode.com/posts/1', 60); // Cache for 60 seconds
//
// if ($data) {
// echo "API Data (cached or fresh):
";
// print_r($data);
// } else {
// echo "Could not retrieve API data.
";
// }
//
// // Subsequent calls within 60 seconds will use the cache
// $data2 = fetchApiWithCache('https://jsonplaceholder.typicode.com/posts/1', 60);
//
// $data_different = fetchApiWithCache('https://jsonplaceholder.typicode.com/posts/2', 300); // Different endpoint, different cache
?>
How it works: This PHP function provides a basic file-based caching mechanism for API responses. It calculates a unique cache key based on the API URL and stores the response in a local file within a specified directory. Before making an API request, it checks if a valid, unexpired cache file exists. If so, it serves the cached data, reducing network calls. Otherwise, it fetches data from the API, stores the fresh response in the cache, and then returns it, improving performance and reducing reliance on external services.