How can caching be implemented in PHP to improve the performance of accessing external APIs?

Caching can be implemented in PHP by storing the response data from external APIs in a cache system like Redis or Memcached. This way, subsequent requests for the same data can be served from the cache instead of making repeated API calls, improving performance and reducing load on the external API.

// Check if data is present in cache
$cacheKey = 'api_data_' . $apiEndpoint;
$cachedData = $cache->get($cacheKey);

if (!$cachedData) {
    // Make API request
    $response = file_get_contents($apiEndpoint);
    
    // Store response in cache
    $cache->set($cacheKey, $response, $cacheTTL);
    
    $data = json_decode($response, true);
} else {
    $data = json_decode($cachedData, true);
}

// Use the $data retrieved from either the cache or the API response