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

Technical Evaluation

Architecture fit:

  • Pros: Aligns perfectly with Laravel’s PSR-6 (Symfony Cache) and PSR-18 (HTTPlug) ecosystems, enabling standardized HTTP response caching for external API calls. Leverages Laravel’s built-in cache adapters (Redis, Memcached, database) without additional infrastructure. Supports modern Laravel versions (8+) and PHP 8.x, reducing versioning conflicts.
  • Cons: Requires HTTPlug (PSR-18) adoption if not already in use (e.g., Guzzle). Limited to HTTP-level caching; application-layer caching (e.g., Eloquent query caching) remains separate. EtagCachePlugin adds complexity for ETag-specific use cases but may not be needed for most Laravel applications.

Integration feasibility:

  • High for Laravel projects using HTTPlug (e.g., php-http/guzzle7-adapter or Symfony’s HttpClient). Composer integration is straightforward, and Laravel’s service container can manage dependencies (cache pool, client, plugin).
  • Medium for projects using Guzzle directly: Requires migrating to HTTPlug or wrapping Guzzle with Http\Adapter\Guzzle7\Client.
  • Low for non-HTTP caching needs (e.g., template caching, database queries).

Technical risk:

  • Minor: MIT license, active maintenance (releases up to 2026), and PSR compliance reduce risk. Laravel’s ecosystem ensures compatibility with Symfony Cache (PSR-6) and HTTPlug (PSR-18).
  • Moderate: Cache invalidation logic must be explicitly configured (e.g., respect_response_cache_directives). Misconfiguration (e.g., caching POST requests) could lead to stale data or race conditions.
  • Critical questions:
    • How will cache keys be generated for Laravel-specific use cases (e.g., API routes with query parameters)?
    • What’s the performance impact of serializing/deserializing responses for cached endpoints?
    • How does this interact with Laravel’s queue system or event listeners for cache invalidation?

Integration Approach

Stack fit:

  • Laravel-native: Works seamlessly with Laravel’s cache drivers (Redis, database, file) and HTTP clients (Symfony’s HttpClient or HTTPlug adapters like php-http/guzzle7-adapter).
  • Example stack:
    // config/app.php
    'http_client' => Http\Client\HttpClient::class,
    'cache' => CacheManager::class,
    
  • Non-HTTP use cases: Not applicable; focus on external API caching (e.g., payment gateways, weather APIs).

Migration path:

  1. Adopt HTTPlug (if not using it):
    • Replace Guzzle with symfony/http-client or wrap Guzzle with Http\Adapter\Guzzle7\Client.
    • Example:
      $client = new Http\Client\HttpClient(
          new Http\Adapter\Guzzle7\Client(),
          ['plugins' => [$cachePlugin]]
      );
      
  2. Configure cache pool:
    • Use Laravel’s cache drivers via Cache\Adapter\* (e.g., Cache\Adapter\Redis\RedisCachePool).
    • Example:
      $cachePool = CacheManager::get('redis')->getPool();
      
  3. Attach plugin:
    • Wrap the client in CachePlugin in a Laravel service provider or container binding.
    • Example:
      $this->app->bind(HttpClient::class, function ($app) {
          $client = new Http\Client\HttpClient();
          $cachePool = $app['cache']->getPool();
          return (new CachePlugin($cachePool))->attachTo($client);
      });
      

Compatibility:

  • Laravel 8/9/10: Fully compatible (tested with Symfony 8+).
  • PHP 8.1–8.5: Supported (no breaking changes in recent versions).
  • Cache backends: PSR-6 adapters (Redis, Memcached, file, database) work out-of-the-box.
  • Edge cases:
    • Stream handling: Plugin detaches streams to avoid serialization warnings (fixed in v1.8.0).
    • ETag/Last-Modified: Automatic validation if headers are present (RFC 7234 compliant).

Sequencing:

  1. Phase 1: Integrate CachePlugin for non-critical external APIs (e.g., rate-limited services).
  2. Phase 2: Extend with custom CacheKeyGenerator or CacheListener for Laravel-specific logic (e.g., cache invalidation on model updates).
  3. Phase 3: Monitor cache hit ratios and adjust TTLs (default_ttl, respect_response_cache_directives).

Operational Impact

Maintenance:

  • Proactive:
    • Monitor X-Cache headers (via AddHeaderCacheListener) to track hit/miss ratios.
    • Set up Laravel’s cache tagging (if using database cache) to invalidate related entries (e.g., cache:tags).
  • Reactive:
    • Cache corruption: Use cache:clear or backend-specific tools (e.g., redis-cli FLUSHDB).
    • Plugin updates: Test with Laravel’s minor version upgrades (e.g., PHP 8.4 → 8.5).

Support:

  • Debugging:
    • Log cache keys and TTLs for troubleshooting stale data:
      $cachePlugin->setCacheListener(new class implements CacheListener {
          public function onCacheHit(ResponseInterface $response) {
              logger()->debug('Cache hit', ['key' => $response->getHeaderLine('X-Cache-Key')]);
          }
      });
      
    • Use blacklisted_paths to exclude problematic endpoints (e.g., /api/webhooks).
  • Fallbacks:
    • Disable caching for critical paths by setting default_ttl => 0.
    • Implement circuit breakers (e.g., php-http/retry-plugin) for external API failures.

Scaling:

  • Horizontal: Cache backends (Redis, Memcached) scale independently of Laravel instances.
  • Vertical: Adjust default_ttl or use CachePolicy to reduce memory usage for high-volume APIs.
  • Cold starts: Pre-warm cache for critical paths during Laravel queue workers’ bootstrapping.

Failure modes:

Scenario Impact Mitigation
Cache backend failure Increased API latency Fallback to default_ttl => 0
Stale cached responses Inconsistent data Use EtagCachePlugin or short TTLs
Key collisions Overwritten cache entries Custom CacheKeyGenerator
Serialization errors Failed cache storage Ensure PSR-7/PSR-17 compliance

Ramp-up:

  • Onboarding:
    • Document cache key generation rules (e.g., CacheKeyGenerator::HEADER_CACHE_KEY for API routes).
    • Example Laravel command to test caching:
      php artisan http:test --cached --url="https://api.example.com/data"
      
  • Training:
    • Highlight respect_response_cache_directives for teams managing API integrations.
    • Show how to extend CacheListener for custom logic (e.g., analytics on cache hits).

Costs:

  • Performance: ~5–10ms overhead per cached request (negligible for external APIs).
  • Storage: Cache size depends on API response sizes and TTLs (monitor with cache:stats).
  • Development: ~2–4 hours to integrate for a Laravel project already using HTTPlug.
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.
hamzi/corewatch
minionfactory/raw-hydrator
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