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

Getting Started

Minimal Setup

  1. Installation:

    composer require friendsofsymfony/http-cache
    

    For Symfony projects, prefer the fos/http-cache-bundle for seamless integration.

  2. First Use Case:

    • Invalidate a URL (e.g., after updating content):
      use FriendsOfSymfony\HTTPCache\Invalidator\InvalidatorInterface;
      use FriendsOfSymfony\HTTPCache\Invalidator\VarnishInvalidator;
      
      $invalidator = new VarnishInvalidator('http://varnish-server:6082');
      $invalidator->invalidate('/path/to/resource');
      
    • Test locally with the NullInvalidator (no-op):
      $invalidator = new NullInvalidator();
      
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Invalidation Strategies:

    • Single URL:
      $invalidator->invalidate('/blog/post-1');
      
    • Tag-Based (Varnish-specific):
      $invalidator->invalidateTag('blog_posts');
      
    • Regex Patterns (for bulk invalidation):
      $invalidator->invalidateRegex('/^\/blog\/post-\d+$/');
      
  2. Integration with Symfony:

    • Use the FOSHttpCacheBundle to auto-register the invalidator as a service:
      # config/packages/fos_http_cache.yaml
      fos_http_cache:
          invalidator:
              varnish:
                  host: 'http://varnish:6082'
      
    • Inject the invalidator into controllers/services:
      public function updatePost(Post $post, InvalidatorInterface $invalidator) {
          $post->updateTitle('New Title');
          $invalidator->invalidate("/blog/{$post->slug}");
      }
      
  3. Testing:

    • Mock the invalidator in tests:
      $mockInvalidator = $this->createMock(InvalidatorInterface::class);
      $mockInvalidator->expects($this->once())->method('invalidate')->with('/test');
      
    • Use NullInvalidator in local/dev environments to bypass real invalidation.
  4. Event-Driven Invalidation:

    • Listen to Symfony events (e.g., kernel.terminate) to invalidate cached responses:
      public function onKernelTerminate(GetResponseForControllerResultEvent $event) {
          $invalidator = $event->getRequest()->get('invalidator');
          $invalidator->invalidate($event->getRequest()->getUri());
      }
      
  5. Custom Invalidators:

    • Extend AbstractInvalidator for non-Varnish proxies (e.g., Nginx):
      class NginxInvalidator extends AbstractInvalidator {
          public function invalidate($url) {
              // Custom Nginx purge logic
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Varnish-Specific Features:

    • Tag-based invalidation (invalidateTag) is Varnish-only. Other proxies (e.g., Nginx) may ignore this.
    • Regex invalidation (invalidateRegex) may not be supported by all proxies. Test thoroughly.
  2. Connection Issues:

    • Ensure the proxy server (e.g., Varnish) is reachable from your PHP process. Use timeouts:
      $invalidator = new VarnishInvalidator('http://varnish:6082', 5.0); // 5s timeout
      
    • Handle exceptions gracefully:
      try {
          $invalidator->invalidate('/path');
      } catch (\RuntimeException $e) {
          \Log::error("Cache invalidation failed: " . $e->getMessage());
      }
      
  3. Performance:

    • Batch invalidations if possible (e.g., invalidate all /blog/* tags at once instead of per-post).
    • Avoid invalidating too aggressively (e.g., invalidating / triggers full cache rebuild).
  4. Symfony Cache vs. HTTP Cache:

    • This package only handles HTTP proxy invalidation, not Symfony’s Cache component. Use both together:
      // Invalidate Symfony cache (e.g., Doctrine, OpCache)
      $cache->clear();
      // Invalidate HTTP cache (Varnish/Nginx)
      $invalidator->invalidate('/path');
      

Debugging Tips

  1. Enable Logging:

    • Configure the VarnishInvalidator to log requests:
      $invalidator = new VarnishInvalidator('http://varnish:6082', null, [
          'logger' => new \Monolog\Logger('cache')
      ]);
      
    • Check Varnish logs (varnishlog) for invalidation failures.
  2. Validate Proxy Configuration:

    • Test invalidation manually via curl:
      curl -X PURGE http://varnish-server:6082/path/to/resource
      
    • Ensure your proxy supports the PURGE method (or equivalent).
  3. Common Errors:

    • 404 on PURGE: The proxy doesn’t support the endpoint. Check your Varnish/Nginx config.
    • Timeouts: Increase the timeout or optimize proxy response times.
    • Permission Denied: Ensure your PHP process has network access to the proxy.

Extension Points

  1. Custom Headers:

    • Pass custom headers to the proxy (e.g., for authentication):
      $invalidator = new VarnishInvalidator('http://varnish:6082', null, [
          'headers' => ['X-Cache-Key' => 'custom_key']
      ]);
      
  2. Retry Logic:

    • Implement retries for transient failures:
      $invalidator = new RetryInvalidator(new VarnishInvalidator('http://varnish:6082'), 3);
      
      (Create a decorator class wrapping InvalidatorInterface.)
  3. Dynamic Proxy Selection:

    • Switch proxies based on environment (e.g., dev, staging, prod):
      $proxyUrl = config('fos_http_cache.proxy_url');
      $invalidator = new VarnishInvalidator($proxyUrl);
      
  4. Metrics:

    • Track invalidation success/failure rates:
      $invalidator = new InstrumentedInvalidator(
          new VarnishInvalidator('http://varnish:6082'),
          new StatsdClient()
      );
      

Configuration Quirks

  1. Symfony Bundle:

    • The bundle requires fos_http_cache to be loaded after framework in config/bundles.php:
      return [
          // ...
          FriendsOfSymfony\FOSHttpCacheBundle\FOSHttpCacheBundle::class => ['all' => true],
      ];
      
    • Environment variables override YAML config:
      # config/packages/fos_http_cache.yaml
      fos_http_cache:
          invalidator:
              varnish:
                  host: '%env(VARNISH_HOST)%'
      
  2. NullInvalidator:

    • Useful for local development, but disable it in production to avoid silent failures:
      # config/packages/fos_http_cache.yaml
      fos_http_cache:
          invalidator: ~ # Disables NullInvalidator in production
      
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