guzzle/cache
Adds response caching to Guzzle HTTP clients. Store and reuse GET responses to cut latency and API calls, with configurable cache pools, TTLs, and cache strategies. Useful for microservices, third‑party APIs, and rate‑limited endpoints.
Installation:
composer require guzzle/cache
Ensure compatibility with Guzzle 3.x (this package is a read-only subtree split).
Basic Usage:
use Guzzle\Cache\Cache;
use Guzzle\Cache\Storage\FileCacheStorage;
// Initialize cache storage (e.g., file-based)
$storage = new FileCacheStorage('/path/to/cache/dir');
$cache = new Cache($storage);
// Store a value
$cache->save('key', 'value', 3600); // Expires in 1 hour
// Retrieve a value
$value = $cache->fetch('key');
First Use Case: Cache HTTP responses to avoid redundant API calls:
use Guzzle\Http\Client;
use Guzzle\Cache\CacheMiddleware;
$client = new Client();
$client->getEmitter()->attach(new CacheMiddleware($cache));
$response = $client->get('https://api.example.com/data');
Middleware Integration:
Use CacheMiddleware to cache HTTP responses globally:
$client = new Client();
$client->getEmitter()->attach(new CacheMiddleware($cache, [
'default_ttl' => 3600,
'private_ttl' => 86400,
]));
Conditional Caching: Cache only successful responses (e.g., 2xx status codes):
$client->getEmitter()->attach(function ($request, $event) use ($cache) {
if ($event->getResponse()->isSuccess()) {
$cache->save($request->getUrl(), $event->getResponse(), 3600);
}
});
Custom Storage:
Extend CacheStorageInterface for database or Redis backends:
class RedisCacheStorage implements CacheStorageInterface {
// Implement save(), fetch(), delete(), etc.
}
Laravel Integration:
Use guzzle/cache with Laravel's HTTP client (if compatible) or wrap it in a service:
$this->app->singleton('cache', function ($app) {
$storage = new FileCacheStorage(storage_path('cache/guzzle'));
return new Cache($storage);
});
Cache Invalidation: Manually clear stale data:
$cache->delete('key'); // Delete specific key
$cache->clear(); // Clear all cached data
Guzzle 3 Compatibility:
guzzlehttp/guzzle (v6+) for newer projects; this package is legacy.Thread Safety:
FileCacheStorage) is not thread-safe. Use locks or switch to Redis/Memcached for concurrent apps.Serialization:
__serialize()/__unserialize().Cache Misses:
Check if keys are being generated correctly (e.g., URL hashing in CacheMiddleware).
$cache->has('key'); // Verify key existence
Storage Issues: Ensure the cache directory is writable:
chmod -R 775 /path/to/cache/dir
Custom Cache Keys:
Override CacheMiddleware::getCacheKey() to customize key generation:
$middleware = new CacheMiddleware($cache, [
'cache_key' => function ($request) {
return md5($request->getUrl() . $request->getMethod());
}
]);
Event Hooks:
Extend CacheMiddleware to log cache hits/misses:
$client->getEmitter()->attach(function ($request, $event) use ($cache) {
if ($cache->has($request->getUrl())) {
Log::debug('Cache hit for', ['url' => $request->getUrl()]);
}
});
Fallback Logic:
Combine with Guzzle\Plugin\Retry to retry failed requests after cache misses:
$client->getEmitter()->attach(new RetryPlugin());
$client->getEmitter()->attach(new CacheMiddleware($cache));
How can I help you explore Laravel packages today?