1. <?php
  2. /**
  3. * Gracefully handles API responses with fallback mechanisms for monitoring.
  4. *
  5. * @param string $apiUrl The URL of the API endpoint.
  6. * @param callable $fallbackFunction A function to execute if the API request fails.
  7. * @param int $retryAttempts Number of times to retry the API request.
  8. * @param int $retryDelay Delay between retry attempts in seconds.
  9. * @return mixed The API response data or the fallback result.
  10. */
  11. function getApiDataWithFallback(string $apiUrl, callable $fallbackFunction, int $retryAttempts = 3, int $retryDelay = 1): mixed
  12. {
  13. for ($i = 0; $i < $retryAttempts; $i++) {
  14. try {
  15. $response = file_get_contents($apiUrl); // Use file_get_contents for simplicity & minimal dependencies
  16. if ($response === false) {
  17. if ($i === $retryAttempts - 1) {
  18. // Last attempt failed, execute the fallback
  19. return $fallbackFunction();
  20. }
  21. sleep($retryDelay);
  22. continue; // Retry
  23. }
  24. $data = json_decode($response, true); // Decode JSON
  25. if (json_last_error() !== JSON_ERROR_NONE) {
  26. if ($i === $retryAttempts - 1) {
  27. return $fallbackFunction();
  28. }
  29. sleep($retryDelay);
  30. continue; // Retry
  31. }
  32. return $data; // Successfully retrieved and decoded data
  33. } catch (Exception $e) {
  34. if ($i === $retryAttempts - 1) {
  35. return $fallbackFunction();
  36. }
  37. sleep($retryDelay);
  38. continue; // Retry
  39. }
  40. }
  41. return $fallbackFunction(); // Should not reach here, but included for safety
  42. }
  43. // Example Usage (Replace with your API and fallback)
  44. /*
  45. function myFallbackFunction(): array {
  46. // Your fallback logic here (e.g., default data, cached data, etc.)
  47. return ['message' => 'API request failed, using fallback data.', 'data' => []];
  48. }
  49. $apiUrl = 'https://api.example.com/data';
  50. $data = getApiDataWithFallback($apiUrl, 'myFallbackFunction');
  51. if (is_array($data)) {
  52. // Process the API data
  53. print_r($data);
  54. } else {
  55. // Process the fallback data
  56. print_r($data);
  57. }
  58. */
  59. ?>

Add your comment