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

Http Cache Laravel Package

friendsofsymfony/http-cache

PHP library to integrate apps with HTTP caching proxies (Varnish, NGINX, Symfony HttpCache, Fastly, Cloudflare). Send efficient cache invalidation/purge and tag requests, abstract proxy features, and test caching/invalidation with PHPUnit tools.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • HTTP Caching Proxy Integration: FOSHttpCache is a highly specialized package for managing HTTP caching proxies (e.g., Varnish, Nginx) in PHP/Laravel applications. It abstracts invalidation logic, making it ideal for performance-critical applications where caching is a core requirement.
  • Symfony-First Design: While Laravel-compatible, the package was originally built for Symfony, meaning some Laravel-specific integrations (e.g., service container binding, event dispatching) may require custom adaptations.
  • Layered Abstraction: The package provides a clean separation between cache invalidation logic and proxy communication, which aligns well with Laravel’s modular architecture (e.g., middleware, service providers).
  • Key Use Cases:
    • Edge Caching: Ideal for Laravel apps behind CDNs or reverse proxies (e.g., Cloudflare, Fastly, Varnish).
    • Cache Invalidation: Simplifies purging stale content (e.g., after POST/PUT/DELETE operations).
    • Testing: Includes tools to mock proxy responses, useful for CI/CD pipelines.

Integration Feasibility

  • Laravel Compatibility:
    • Service Container: Laravel’s IoC container is similar but not identical to Symfony’s. The package will need custom binding (e.g., via AppServiceProvider) to register the HttpCacheInvalidator and related services.
    • Middleware: The package’s HttpCacheMiddleware can be directly integrated into Laravel’s middleware stack (e.g., Kernel.php).
    • Events: Laravel’s event system is compatible with Symfony’s event dispatching (via symfony/event-dispatcher), but custom event listeners may be needed for Laravel-specific hooks (e.g., Model::saved).
  • Proxy Support:
    • Varnish/Nginx: Native support via Purge API or Ban Lists.
    • Cloudflare/Fastly: Requires custom proxy adapters (e.g., HTTP API clients).
  • Database-Driven Caching: If Laravel uses database-backed caching (e.g., Redis, Memcached), FOSHttpCache can complement it by handling HTTP-level caching.

Technical Risk

Risk Area Severity Mitigation Strategy
Symfony Dependency Medium Abstract Symfony-specific components (e.g., EventDispatcher) behind interfaces.
Middleware Conflicts Low Test with Laravel’s middleware priority system (e.g., web vs. api groups).
Proxy API Changes Medium Use feature flags for proxy-specific logic and monitor for breaking changes.
Testing Complexity High Leverage the package’s mocking utilities but supplement with Laravel’s HttpTests.
Performance Overhead Low Benchmark invalidation requests; optimize with async processing (e.g., queues).

Key Questions

  1. Proxy Strategy:
    • Which HTTP caching proxies (Varnish/Nginx/Cloudflare) are in scope? Are custom adapters needed?
  2. Invalidation Granularity:
    • Will invalidations be URL-based (e.g., /posts/1) or tag-based (e.g., posts)?
  3. Fallback Mechanism:
    • How should the app behave if the proxy is unreachable (e.g., gracefully degrade or fail fast)?
  4. Laravel-Specific Hooks:
    • Should invalidations trigger on Eloquent events, API routes, or both?
  5. Monitoring:
    • Are there requirements for tracking cache hit/miss ratios or invalidation success rates?
  6. CI/CD Impact:
    • How will proxy-dependent tests be isolated in the test suite (e.g., Dockerized Varnish)?

Integration Approach

Stack Fit

  • Laravel Core:
    • Service Provider: Register the HttpCacheInvalidator and proxy adapters.
    • Middleware: Insert HttpCacheMiddleware before route handling (to validate cache headers).
    • Events: Use Laravel’s Event facade or bridge Symfony’s EventDispatcher.
  • Proxy Layer:
    • Varnish/Nginx: Use built-in Purge or Ban endpoints.
    • Cloudflare/Fastly: Implement custom HttpClient adapters (e.g., Guzzle-based).
  • Database Layer:
    • Cache Tags: Store invalidation tags in a cache_tags table (if using tag-based invalidation).
  • Testing:
    • Mock Proxies: Use FOSHttpCache’s MockProxyClient in unit tests.
    • Integration Tests: Spin up a Dockerized Varnish for end-to-end testing.

Migration Path

  1. Phase 1: Proof of Concept (2-4 weeks)
    • Integrate the package in a non-production environment.
    • Test with a single proxy (e.g., Varnish) and basic invalidation routes.
    • Validate middleware behavior with Laravel’s routing.
  2. Phase 2: Core Integration (4-6 weeks)
    • Implement proxy adapters for all target proxies (e.g., Cloudflare).
    • Add Laravel-specific event listeners (e.g., ModelObserver for Eloquent).
    • Configure cache tagging if needed.
  3. Phase 3: Optimization & Monitoring (2-3 weeks)
    • Benchmark invalidation latency and optimize async processing (e.g., queues).
    • Add health checks for proxy connectivity.
    • Implement logging for invalidation events.

Compatibility

Component Compatibility Notes
Laravel 10+ Fully compatible; minor adjustments for Symfony components (e.g., HttpFoundation).
PHP 8.1+ Required for modern Laravel versions; no breaking changes expected.
Symfony Components HttpFoundation, EventDispatcher, and HttpClient are optional dependencies.
Varnish/Nginx Native support; ensure proxy version aligns with package’s tested versions.
Cloudflare/Fastly Requires custom HTTP clients (not bundled).

Sequencing

  1. Dependency Setup:
    • Install via Composer: composer require friendsofsymfony/http-cache.
    • Resolve Symfony component conflicts (e.g., symfony/http-foundation) via replace in composer.json.
  2. Service Registration:
    • Bind the invalidator in AppServiceProvider::boot():
      $this->app->singleton(HttpCacheInvalidator::class, function ($app) {
          return new HttpCacheInvalidator(
              new PurgeClient($app['http.client'], 'http://varnish:6082'),
              $app['events']
          );
      });
      
  3. Middleware Integration:
    • Add to app/Http/Kernel.php before route middleware:
      protected $middleware = [
          \FOS\HttpCache\HttpCacheMiddleware::class,
      ];
      
  4. Invalidation Logic:
    • Trigger invalidations via:
      • Routes: route('cache_purge', ['path' => '/posts/1']).
      • Events: Listen to eloquent.saved and call $invalidator->invalidatePath('/posts/1').
  5. Testing:
    • Mock the proxy in unit tests:
      $mockProxy = new MockProxyClient();
      $invalidator = new HttpCacheInvalidator($mockProxy);
      

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor Symfony component versions (e.g., HttpFoundation) for breaking changes.
    • Pin versions in composer.json if proxy APIs are unstable.
  • Proxy-Specific Logic:
    • Maintain adapter classes for each proxy (e.g., CloudflarePurgeAdapter).
    • Document deprecation paths for proxy API changes.
  • Laravel Ecosystem:
    • Stay aligned with Laravel’s middleware/routing changes (e.g., PSR-15 middleware).

Support

  • Debugging:
    • Log invalidation requests and proxy responses for auditability.
    • Implement a health endpoint (/health/cache) to verify proxy connectivity.
  • Common Issues:
    • Race Conditions: Ensure invalidations are idempotent (e.g., retry failed requests).
    • Permission Errors: Validate proxy credentials are securely stored (e.g., env vars).
  • Support Channels:
    • Leverage FOSHttpCache’s GitHub issues for proxy-specific bugs.
    • Use Laravel’s Slack/Discord for integration questions.

Scaling

  • Horizontal Scaling:
    • Stateless Invalidations: Design invalidation logic to work across multiple app instances.
    • Queue-Based Processing: Offload
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky