<?php
/**
* API Caching with Manual Overrides
*
* This function caches the results of an API call. It allows for manual
* overriding of the cache if needed.
*
* @param callable $api_call A callable (function) that makes the API call.
* Should return the API response data.
* @param string $cache_key A unique key for the cache entry.
* @param int $cache_duration Cache duration in seconds. Default: 3600 (1 hour).
* @return mixed The cached result or the result of the API call if not cached.
*/
function cache_api_response(callable $api_call, string $cache_key, int $cache_duration = 3600)
{
static $cache = []; // Static array to store cached data.
// Check if the data is already in the cache.
if (isset($cache[$cache_key])) {
$timestamp = time();
if ($timestamp - $cache[$cache_key]['timestamp'] < $cache_duration) {
// Cache hit: return the cached data.
return $cache[$cache_key]['data'];
} else {
// Cache expired: remove the expired entry.
unset($cache[$cache_key]);
}
}
// Cache miss: make the API call.
$data = $api_call();
// Store the data in the cache.
$cache[$cache_key] = [
'data' => $data,
'timestamp' => time(),
];
return $data;
}
/**
* Example Usage:
*/
/**
* Simulate an API call. Replace this with your actual API call.
* This example returns some dummy data.
* @return array
*/
function get_api_data(): array {
// Simulate an API request
sleep(1); // Simulate network latency
return ['message' => 'API Response Data', 'timestamp' => time()];
}
// Example 1: Using the cache
$cache_key = 'my_api_data';
$data = cache_api_response(function () { return get_api_data(); }, $cache_key);
echo "Data from cache: " . json_encode($data) . "\n";
// Example 2: Manual override
$data = cache_api_response(function () { return get_api_data(); }, $cache_key, 60); //Cache for 60 seconds
echo "Data after 60 seconds from cache: " . json_encode($data) . "\n";
// Example 3: API call without caching (override)
$data = get_api_data(); //This will bypass the cache.
echo "Data from API call (no cache): " . json_encode($data) . "\n";
?>
Add your comment