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 Plugin Laravel Package

php-http/cache-plugin

PSR-6 cache plugin for HTTPlug clients. Automatically caches HTTP responses (and can serve stale on error) with configurable cache strategies, TTL, and cache key generation. Drop it into your plugin chain to cut latency and reduce repeated requests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package and dependencies:

    composer require php-http/cache-plugin php-http/httplug-bundle cache/simple-filesystem-adapter
    

    (Replace simple-filesystem-adapter with your preferred PSR-6 cache, e.g., predis/predis for Redis.)

  2. Configure the cache pool (e.g., in config/cache.php):

    'connections' => [
        'http_cache' => [
            'driver' => 'redis',
            'host' => env('REDIS_HOST', '127.0.0.1'),
            // ... other Redis config
        ],
    ],
    
  3. Wrap your HTTP client (e.g., in a service provider):

    use Http\Client\Common\Plugin\CachePlugin;
    use Http\Client\Common\Plugin\CachePlugin\CacheKeyGenerator\HeaderCacheKeyGenerator;
    use Http\Client\Common\Plugin\CachePlugin\CachePolicy\CachePolicy;
    use Http\Client\Common\Plugin\CachePlugin\CachePolicy\CachePolicyInterface;
    use Http\Client\Common\Plugin\CachePlugin\CachePolicy\CachePolicyFactory;
    use Http\Client\Common\Plugin\CachePlugin\CachePolicy\CachePolicyFactoryInterface;
    use Http\Client\Common\Plugin\CachePlugin\CachePolicy\CachePolicyFactoryInterface;
    
    public function register()
    {
        $this->app->singleton('http.client.cached', function ($app) {
            $client = $app['http.client']; // Your base HTTPlug client
            $cachePool = $app['cache']->connection('http_cache')->getPsr6Connection();
    
            $cachePlugin = new CachePlugin(
                $cachePool,
                new HeaderCacheKeyGenerator(), // Customize key generation
                new CachePolicyFactory() // Customize cache policies
            );
    
            return $cachePlugin->attachTo($client);
        });
    }
    
  4. First use case: Cache API responses for a Laravel controller:

    public function getData()
    {
        $cachedClient = app('http.client.cached');
        $response = $cachedClient->get('https://api.example.com/data');
        return json_decode($response->getBody(), true);
    }
    

Implementation Patterns

1. Caching Strategies

  • Automatic caching: The plugin respects Cache-Control headers by default. Use respect_response_cache_directives to fine-tune:
    $cachePlugin = new CachePlugin($cachePool, null, [
        'respect_response_cache_directives' => ['max-age', 'must-revalidate'],
    ]);
    
  • ETag-based caching: For dynamic content with ETag headers, use EtagCachePlugin:
    $etagPlugin = new EtagCachePlugin($cachePool);
    $client = $etagPlugin->attachTo($client);
    
  • Blacklist paths: Exclude sensitive endpoints (e.g., /admin/*):
    $cachePlugin = new CachePlugin($cachePool, null, [
        'blacklisted_paths' => ['/admin/', '/api/tokens'],
    ]);
    

2. Key Generation

  • Default: Uses SimpleGenerator (hashes URL + method + headers).
  • Custom: Implement CacheKeyGenerator for complex logic (e.g., include query params):
    use Http\Client\Common\Plugin\CachePlugin\CacheKeyGenerator\CacheKeyGeneratorInterface;
    
    class QueryParamCacheKeyGenerator implements CacheKeyGeneratorInterface
    {
        public function generateKey(RequestInterface $request): string
        {
            return sha1($request->getUri() . $request->getMethod() . $request->getBody());
        }
    }
    

3. Cache Listeners

  • Debugging: Add X-Cache headers to responses:
    use Http\Client\Common\Plugin\CachePlugin\CacheListener\AddHeaderCacheListener;
    
    $listener = new AddHeaderCacheListener();
    $cachePlugin = new CachePlugin($cachePool, null, [
        'cache_listeners' => [$listener],
    ]);
    
  • Custom logic: Implement CacheListenerInterface to log cache hits/misses or invalidate related caches.

4. Integration with Laravel

  • Service Container: Bind the cached client to the container (as shown in Getting Started).
  • Middleware: Use the cached client in middleware to cache API responses globally:
    public function handle($request, Closure $next)
    {
        $cachedClient = app('http.client.cached');
        $response = $cachedClient->sendRequest($request->toPsrRequest());
        return response($response->getBody(), $response->getStatusCode(), $response->getHeaders());
    }
    
  • Commands/Jobs: Cache external API calls in background jobs:
    public function handle()
    {
        $client = app('http.client.cached');
        $response = $client->get('https://api.example.com/updates');
        // Process response...
    }
    

5. Testing

  • Mock the cache: Use Cache\Adapter\PHPArray\ArrayCachePool for unit tests:
    $cachePool = new ArrayCachePool();
    $cachePlugin = new CachePlugin($cachePool);
    $cachedClient = $cachePlugin->attachTo($client);
    
  • Verify cache behavior: Assert X-Cache headers or check cache keys:
    $this->assertEquals('HIT', $response->getHeader('X-Cache')[0]);
    

Gotchas and Tips

Pitfalls

  1. Stream Handling:

    • The plugin detaches streams during serialization to avoid warnings. If you need to read the stream multiple times, ensure the response is rewound:
      $response->getBody()->rewind();
      
    • Fix: Use StreamFactoryInterface (PSR-17) to recreate streams if needed.
  2. Cache Key Collisions:

    • Default key generation may collide for similar URLs (e.g., /users?page=1 vs. /users?page=2).
    • Solution: Use HeaderCacheKeyGenerator or a custom generator to include query params.
  3. TTL Conflicts:

    • default_ttl (e.g., 0 for session caching) can override Cache-Control headers.
    • Tip: Set default_ttl to null to rely solely on response headers:
      $cachePlugin = new CachePlugin($cachePool, null, ['default_ttl' => null]);
      
  4. ETag/Last-Modified Validation:

    • The plugin automatically validates cached responses using ETag/Last-Modified if the server provides them.
    • Gotcha: If the server sends inconsistent headers (e.g., ETag but no Last-Modified), validation may fail silently.
    • Debug: Check X-Cache headers or enable cache_listeners to log validation attempts.
  5. Blacklist Regex:

    • blacklisted_paths uses regex, not glob patterns. Escape special chars:
      'blacklisted_paths' => ['/api/v1/.*/webhooks'], // Matches `/api/v1/users/webhooks`
      
  6. Symfony HttpClient:

    • If using Symfony’s HttpClient, ensure you’re using the PSR-18 version (not the legacy HttpClient):
      $client = SymfonyHttpClient::create(['base_uri' => 'https://api.example.com']);
      

Debugging Tips

  1. Enable Cache Headers: Add AddHeaderCacheListener to inspect cache behavior:

    $cachePlugin = new CachePlugin($cachePool, null, [
        'cache_listeners' => [new AddHeaderCacheListener()],
    ]);
    
    • X-Cache: HIT → Response served from cache.
    • X-Cache: MISS → Response fetched from origin.
  2. Inspect Cache Keys: Log keys to verify they’re unique:

    $cachePlugin->getCacheKeyGenerator()->generateKey($request);
    
  3. Clear Cache Manually: Use your PSR-6 cache adapter’s clear() method:

    $cachePool->clear();
    
  4. Test with default_ttl = 1: Set a short TTL (e.g., 1 second) to verify cache invalidation:

    $cachePlugin = new CachePlugin($cachePool, null, ['default_ttl' => 1]);
    

Extension Points

  1. Custom Cache Policy: Implement CachePolicyInterface to define dynamic TTLs or cache rules:
    class DynamicCachePolicy implements CachePolicyInterface
    {
        public function getTtl(RequestInterface $request, ResponseInterface $response): ?int
        {
            if ($request->getUri()->getPath() === '/promotions') {
                return 3600; //
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai