1. <?php
  2. /**
  3. * Simple HTTP response caching for scheduled runs.
  4. *
  5. * @param callable $callback A function that returns an HTTP response object.
  6. * @param string $cache_file The file to store the cached results.
  7. * @param int $cache_duration The cache duration in seconds (default: 3600).
  8. * @return mixed The cached response, or the result of the callback if no cache exists.
  9. */
  10. function cache_http_response(callable $callback, string $cache_file, int $cache_duration = 3600)
  11. {
  12. // Check if the cache file exists.
  13. if (file_exists($cache_file)) {
  14. // Read the cached response from the file.
  15. $cached_response = file_get_contents($cache_file);
  16. // If the cache is expired, clear it.
  17. if (time() - filemtime($cache_file) > $cache_duration) {
  18. file_delete($cache_file);
  19. $cached_response = null;
  20. }
  21. // Decode the cached response (assuming it's JSON).
  22. if ($cached_response !== null) {
  23. $cached_response = json_decode($cached_response, true);
  24. }
  25. }
  26. // If a cached response exists and is valid, return it.
  27. if ($cached_response !== null) {
  28. return $cached_response;
  29. }
  30. // Otherwise, execute the callback and cache the result.
  31. $response = $callback();
  32. // Encode the response to JSON and write it to the cache file.
  33. file_put_contents($cache_file, json_encode($response));
  34. return $response;
  35. }
  36. /**
  37. * Example usage:
  38. *
  39. * Define a function that makes an HTTP request.
  40. *
  41. * function get_data_from_api() {
  42. * // Your HTTP request logic here
  43. * $response = file_get_contents("https://example.com/api/data");
  44. * return $response;
  45. * }
  46. *
  47. * // Cache the results of the HTTP request.
  48. * $cached_data = cache_http_response(
  49. * 'get_data_from_api',
  50. * 'cache/api_data.json',
  51. * 86400 // Cache for 24 hours
  52. * );
  53. *
  54. * // Use the cached data.
  55. * echo $cached_data;
  56. */
  57. ?>

Add your comment