Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cache Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require guzzle/cache
    

    Ensure compatibility with Guzzle 3.x (this package is a read-only subtree split).

  2. 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');
    
  3. 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');
    

Implementation Patterns

Common Workflows

  1. Middleware Integration: Use CacheMiddleware to cache HTTP responses globally:

    $client = new Client();
    $client->getEmitter()->attach(new CacheMiddleware($cache, [
        'default_ttl' => 3600,
        'private_ttl' => 86400,
    ]));
    
  2. 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);
        }
    });
    
  3. Custom Storage: Extend CacheStorageInterface for database or Redis backends:

    class RedisCacheStorage implements CacheStorageInterface {
        // Implement save(), fetch(), delete(), etc.
    }
    

Integration Tips

  • 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
    

Gotchas and Tips

Pitfalls

  1. Guzzle 3 Compatibility:

    • This package is Guzzle 3.x only. Avoid mixing with Guzzle 6/7.
    • Use guzzlehttp/guzzle (v6+) for newer projects; this package is legacy.
  2. Thread Safety:

    • File-based storage (FileCacheStorage) is not thread-safe. Use locks or switch to Redis/Memcached for concurrent apps.
  3. Serialization:

    • Only serializable data can be cached. Avoid objects without __serialize()/__unserialize().

Debugging

  • 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
    

Extension Points

  1. Custom Cache Keys: Override CacheMiddleware::getCacheKey() to customize key generation:

    $middleware = new CacheMiddleware($cache, [
        'cache_key' => function ($request) {
            return md5($request->getUrl() . $request->getMethod());
        }
    ]);
    
  2. 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()]);
        }
    });
    
  3. 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));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
phpshko/laravel-livewire-depdrop
larasell-dev/larasell
calliostro/spotify-bundle
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer