<?php
/**
* Gracefully handles API responses with fallback mechanisms for monitoring.
*
* @param string $apiUrl The URL of the API endpoint.
* @param callable $fallbackFunction A function to execute if the API request fails.
* @param int $retryAttempts Number of times to retry the API request.
* @param int $retryDelay Delay between retry attempts in seconds.
* @return mixed The API response data or the fallback result.
*/
function getApiDataWithFallback(string $apiUrl, callable $fallbackFunction, int $retryAttempts = 3, int $retryDelay = 1): mixed
{
for ($i = 0; $i < $retryAttempts; $i++) {
try {
$response = file_get_contents($apiUrl); // Use file_get_contents for simplicity & minimal dependencies
if ($response === false) {
if ($i === $retryAttempts - 1) {
// Last attempt failed, execute the fallback
return $fallbackFunction();
}
sleep($retryDelay);
continue; // Retry
}
$data = json_decode($response, true); // Decode JSON
if (json_last_error() !== JSON_ERROR_NONE) {
if ($i === $retryAttempts - 1) {
return $fallbackFunction();
}
sleep($retryDelay);
continue; // Retry
}
return $data; // Successfully retrieved and decoded data
} catch (Exception $e) {
if ($i === $retryAttempts - 1) {
return $fallbackFunction();
}
sleep($retryDelay);
continue; // Retry
}
}
return $fallbackFunction(); // Should not reach here, but included for safety
}
// Example Usage (Replace with your API and fallback)
/*
function myFallbackFunction(): array {
// Your fallback logic here (e.g., default data, cached data, etc.)
return ['message' => 'API request failed, using fallback data.', 'data' => []];
}
$apiUrl = 'https://api.example.com/data';
$data = getApiDataWithFallback($apiUrl, 'myFallbackFunction');
if (is_array($data)) {
// Process the API data
print_r($data);
} else {
// Process the fallback data
print_r($data);
}
*/
?>
Add your comment