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

driebit/http-cache-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require driebit/http-cache-bundle
    

    (Note: While deprecated, this package remains functional for legacy systems.)

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        Driebit\HttpCacheBundle\DriebitHttpCacheBundle::class => ['all' => true],
    ];
    
  3. Configure Cache Clients: Edit config/packages/driebit_http_cache.yaml:

    driebit_http_cache:
        clients:
            varnish:
                type: 'varnish'
                host: '127.0.0.1'
                port: 6082
                purge_url: 'http://%s:%d/%s'
    
  4. First Use Case: Purge a URL via a controller:

    use Driebit\HttpCacheBundle\Manager\CacheManager;
    
    class CacheController extends AbstractController
    {
        public function purge(CacheManager $cacheManager)
        {
            $cacheManager->purge('varnish', '/cached-path');
            return new Response('Purged!');
        }
    }
    

Implementation Patterns

Core Workflows

  1. Purging Strategies:

    • Single URL:
      $cacheManager->purge('varnish', '/path/to/resource');
      
    • Bulk Purge:
      $cacheManager->purgeMultiple('varnish', ['/path1', '/path2']);
      
    • Tag-Based Invalidation (if supported by cache client):
      $cacheManager->purgeByTag('varnish', 'user-profile');
      
  2. Integration with Symfony Events: Listen to kernel.terminate for post-request purges:

    // config/services.yaml
    services:
        App\EventListener\CachePurgerListener:
            tags:
                - { name: 'kernel.event_listener', event: 'kernel.terminate', method: 'onTerminate' }
    
    // src/EventListener/CachePurgerListener.php
    class CachePurgerListener
    {
        public function onTerminate(Request $request, CacheManager $cacheManager)
        {
            if ($request->isXmlHttpRequest()) {
                $cacheManager->purge('varnish', $request->getUri());
            }
        }
    }
    
  3. Custom Cache Clients: Extend Driebit\HttpCacheBundle\Client\AbstractHttpCacheClient:

    class CustomCacheClient extends AbstractHttpCacheClient
    {
        protected function doPurge($url)
        {
            // Custom logic (e.g., API call to your cache)
            file_put_contents('php://stdout', "Purging: $url\n");
        }
    }
    

    Register in config:

    driebit_http_cache:
        clients:
            custom:
                type: 'custom'
                class: 'App\Cache\CustomCacheClient'
    
  4. Conditional Purging: Use Symfony’s Cache component to check if content is stale before purging:

    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
    
    class ConditionalCachePurger implements CacheWarmerInterface
    {
        public function isOptional(): bool { return true; }
    
        public function warmUp($cacheDir): array
        {
            $request = Request::createFromGlobals();
            if ($this->isContentStale($request)) {
                $cacheManager->purge('varnish', $request->getUri());
            }
            return [];
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

    • This bundle is deprecated in favor of FOSHttpCacheBundle. Migrate if possible.
    • Check for breaking changes between versions (e.g., Symfony 4+ compatibility).
  2. Performance Impact:

    • Network Latency: Purging remote caches (e.g., Varnish) adds HTTP overhead. Batch purges where possible.
    • Synchronous Calls: By default, purges are synchronous. For async behavior, use a message queue (e.g., Symfony Messenger) to defer invalidations.
  3. Configuration Quirks:

    • Port Misconfiguration: Ensure port in driebit_http_cache.yaml matches your cache server’s actual port (e.g., Varnish’s default is 6082 for admin).
    • URL Formatting: The purge_url template must support %s (host), %d (port), and %s (path). Example:
      purge_url: 'http://%s:%d/purge/%s'  # Varnish 4+ format
      
  4. Debugging:

    • Silent Failures: If purges fail silently, enable debug logging:
      # config/packages/monolog.yaml
      monolog:
          handlers:
              cache:
                  type: stream
                  path: "%kernel.logs_dir%/cache.log"
                  level: debug
      
    • Test Locally: Use a mock cache client for development:
      class MockCacheClient extends AbstractHttpCacheClient
      {
          public function purge($url)
          {
              file_put_contents('php://stdout', "Mock purge: $url\n");
          }
      }
      

Tips

  1. Environment-Specific Configs: Override cache settings per environment (e.g., disable purging in dev):

    # config/packages/dev/driebit_http_cache.yaml
    driebit_http_cache:
        clients:
            varnish:
                enabled: false
    
  2. Tag-Based Invalidation: If your cache supports tags (e.g., Varnish with ban), use them for granular control:

    $cacheManager->purgeByTag('varnish', 'product-' . $productId);
    
  3. Rate Limiting: Throttle purge requests to avoid overwhelming your cache server:

    use Symfony\Component\RateLimiter\RateLimiterFactory;
    
    class ThrottledCacheManager
    {
        public function purge($clientName, $url)
        {
            $rateLimiter = RateLimiterFactory::create(['limit' => 10, 'interval' => '1 minute']);
            if ($rateLimiter->consume()) {
                $cacheManager->purge($clientName, $url);
            }
        }
    }
    
  4. Testing:

    • Use Driebit\HttpCacheBundle\Client\NullHttpCacheClient for tests:
      # config/packages/test/driebit_http_cache.yaml
      driebit_http_cache:
          clients:
              varnish:
                  type: 'null'
      
    • Mock the CacheManager in PHPUnit:
      $cacheManager = $this->createMock(CacheManager::class);
      $cacheManager->expects($this->once())
                   ->method('purge')
                   ->with('varnish', '/test');
      
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.
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
spatie/mailcoach-vapor