1. <?php
  2. /**
  3. * API Caching with Manual Overrides
  4. *
  5. * This function caches the results of an API call. It allows for manual
  6. * overriding of the cache if needed.
  7. *
  8. * @param callable $api_call A callable (function) that makes the API call.
  9. * Should return the API response data.
  10. * @param string $cache_key A unique key for the cache entry.
  11. * @param int $cache_duration Cache duration in seconds. Default: 3600 (1 hour).
  12. * @return mixed The cached result or the result of the API call if not cached.
  13. */
  14. function cache_api_response(callable $api_call, string $cache_key, int $cache_duration = 3600)
  15. {
  16. static $cache = []; // Static array to store cached data.
  17. // Check if the data is already in the cache.
  18. if (isset($cache[$cache_key])) {
  19. $timestamp = time();
  20. if ($timestamp - $cache[$cache_key]['timestamp'] < $cache_duration) {
  21. // Cache hit: return the cached data.
  22. return $cache[$cache_key]['data'];
  23. } else {
  24. // Cache expired: remove the expired entry.
  25. unset($cache[$cache_key]);
  26. }
  27. }
  28. // Cache miss: make the API call.
  29. $data = $api_call();
  30. // Store the data in the cache.
  31. $cache[$cache_key] = [
  32. 'data' => $data,
  33. 'timestamp' => time(),
  34. ];
  35. return $data;
  36. }
  37. /**
  38. * Example Usage:
  39. */
  40. /**
  41. * Simulate an API call. Replace this with your actual API call.
  42. * This example returns some dummy data.
  43. * @return array
  44. */
  45. function get_api_data(): array {
  46. // Simulate an API request
  47. sleep(1); // Simulate network latency
  48. return ['message' => 'API Response Data', 'timestamp' => time()];
  49. }
  50. // Example 1: Using the cache
  51. $cache_key = 'my_api_data';
  52. $data = cache_api_response(function () { return get_api_data(); }, $cache_key);
  53. echo "Data from cache: " . json_encode($data) . "\n";
  54. // Example 2: Manual override
  55. $data = cache_api_response(function () { return get_api_data(); }, $cache_key, 60); //Cache for 60 seconds
  56. echo "Data after 60 seconds from cache: " . json_encode($data) . "\n";
  57. // Example 3: API call without caching (override)
  58. $data = get_api_data(); //This will bypass the cache.
  59. echo "Data from API call (no cache): " . json_encode($data) . "\n";
  60. ?>

Add your comment