PHP
Caching External API Responses in PHP with TTL
Implement a basic caching mechanism in PHP to store external API responses, reducing redundant requests and improving application performance with a Time-To-Live.
<?php
class ApiCache {
private $cacheDir;
private $defaultTtl;
public function __construct($cacheDir = __DIR__ . '/cache', $defaultTtl = 3600) {
$this->cacheDir = $cacheDir;
$this->defaultTtl = $defaultTtl;
if (!is_dir($this->cacheDir)) {
mkdir($this->cacheDir, 0777, true);
}
}
private function getCacheFilePath($key) {
return $this->cacheDir . '/' . md5($key) . '.cache';
}
public function get($key) {
$filePath = $this->getCacheFilePath($key);
if (file_exists($filePath)) {
$content = file_get_contents($filePath);
$data = json_decode($content, true);
if ($data && isset($data['expiry']) && $data['expiry'] > time()) {
return $data['value'];
} else {
// Cache expired, delete it
unlink($filePath);
}
}
return null;
}
public function set($key, $value, $ttl = null) {
$ttl = $ttl ?? $this->defaultTtl;
$filePath = $this->getCacheFilePath($key);
$data = [
'expiry' => time() + $ttl,
'value' => $value
];
file_put_contents($filePath, json_encode($data));
}
public function remember($key, callable $callback, $ttl = null) {
$cachedValue = $this->get($key);
if ($cachedValue !== null) {
return $cachedValue;
}
$liveValue = $callback();
$this->set($key, $liveValue, $ttl);
return $liveValue;
}
}
// Example Usage:
// $apiCache = new ApiCache();
// function fetch_user_data_from_api($userId) {
// echo "Fetching user {$userId} from API...
";
// // Simulate API call delay
// sleep(1);
// return ['id' => $userId, 'name' => 'User ' . $userId, 'email' => "user{$userId}@example.com"];
// }
// // First call - fetches from API and caches for 60 seconds
// $user1 = $apiCache->remember('user_1_data', function() {
// return fetch_user_data_from_api(1);
// }, 60);
// var_dump($user1);
// // Second call (within 60 seconds) - fetches from cache
// $user1_cached = $apiCache->remember('user_1_data', function() {
// return fetch_user_data_from_api(1);
// }); // Uses default TTL if not specified
// var_dump($user1_cached);
?>
How it works: This PHP snippet provides a simple file-based caching mechanism for external API responses. The `ApiCache` class allows storing and retrieving data associated with a key, respecting a Time-To-Live (TTL). When data is requested using the `remember` method, it first checks if a valid, unexpired entry exists in the cache. If found, it returns the cached data immediately. Otherwise, it executes a provided callback function (which typically fetches data from the API), stores the result in the cache with the specified TTL, and then returns the live data. This pattern significantly reduces redundant API calls.