<?php
/**
* Simple HTTP response caching for scheduled runs.
*
* @param callable $callback A function that returns an HTTP response object.
* @param string $cache_file The file to store the cached results.
* @param int $cache_duration The cache duration in seconds (default: 3600).
* @return mixed The cached response, or the result of the callback if no cache exists.
*/
function cache_http_response(callable $callback, string $cache_file, int $cache_duration = 3600)
{
// Check if the cache file exists.
if (file_exists($cache_file)) {
// Read the cached response from the file.
$cached_response = file_get_contents($cache_file);
// If the cache is expired, clear it.
if (time() - filemtime($cache_file) > $cache_duration) {
file_delete($cache_file);
$cached_response = null;
}
// Decode the cached response (assuming it's JSON).
if ($cached_response !== null) {
$cached_response = json_decode($cached_response, true);
}
}
// If a cached response exists and is valid, return it.
if ($cached_response !== null) {
return $cached_response;
}
// Otherwise, execute the callback and cache the result.
$response = $callback();
// Encode the response to JSON and write it to the cache file.
file_put_contents($cache_file, json_encode($response));
return $response;
}
/**
* Example usage:
*
* Define a function that makes an HTTP request.
*
* function get_data_from_api() {
* // Your HTTP request logic here
* $response = file_get_contents("https://example.com/api/data");
* return $response;
* }
*
* // Cache the results of the HTTP request.
* $cached_data = cache_http_response(
* 'get_data_from_api',
* 'cache/api_data.json',
* 86400 // Cache for 24 hours
* );
*
* // Use the cached data.
* echo $cached_data;
*/
?>
Add your comment