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

Varnish Bundle Laravel Package

donkeycode/varnish-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require donkeycode/varnish-bundle
    

    Add to config/bundles.php:

    DonkeCode\VarnishBundle\DonkeCodeVarnishBundle::class => ['all' => true],
    
  2. Publish Config

    php bin/console donkecode:varnish:install
    

    This generates config/packages/donkecode_varnish.yaml with default settings.

  3. First Use Case: Cache by User Group Annotate a controller method with:

    use DonkeCode\VarnishBundle\Annotation\Varnish;
    
    /**
     * @Varnish(group="premium_users")
     */
    public function premiumContent()
    {
        return new Response('Premium content');
    }
    

    Ensure VarnishListener is enabled in config/packages/donkecode_varnish.yaml:

    listeners:
        varnish: true
    

Implementation Patterns

Workflow: Conditional Caching

  1. Annotation-Based Caching

    • Use @Varnish on controller methods with:
      • group: Cache by Symfony security group (e.g., ROLE_ADMIN).
      • id: Cache by user ID (e.g., id="%user.id%").
      • ttl: Custom TTL (default: 3600 seconds).
    /**
     * @Varnish(group="ROLE_EDITOR", ttl=86400)
     */
    public function editorDashboard()
    
  2. Dynamic Rules via Event Subscribers Extend caching logic by subscribing to varnish.cache_key event:

    use DonkeCode\VarnishBundle\Event\CacheKeyEvent;
    
    public function onCacheKey(CacheKeyEvent $event)
    {
        if ($event->getUser() && $event->getUser()->isVerified()) {
            $event->setCacheKey('verified_' . $event->getCacheKey());
        }
    }
    

    Register in services.yaml:

    services:
        App\EventSubscriber\VarnishSubscriber:
            tags:
                - { name: kernel.event_subscriber }
    
  3. Integration with Symfony Cache Use VarnishCache as a drop-in replacement for Symfony’s cache:

    use DonkeCode\VarnishBundle\Cache\VarnishCache;
    
    public function __construct(private VarnishCache $varnishCache) {}
    
    public function getCachedData()
    {
        return $this->varnishCache->get('my_key', function() {
            return $this->fetchExpensiveData();
        });
    }
    
  4. CLI Management

    • Clear Cache: php bin/console cache:clear varnish
    • Warm Cache: php bin/console cache:warmup varnish

Gotchas and Tips

Pitfalls

  1. Annotation Parsing

    • Ensure annotations is enabled in framework config (framework: { annotations: true }).
    • Debug missing annotations with:
      php bin/console debug:container DonkeCode\VarnishBundle\DependencyInjection\Compiler\VarnishPass
      
  2. User Context

    • The bundle relies on Symfony’s SecurityContext. If no user is authenticated, caching falls back to public cache.
    • Test with anonymous users to avoid unexpected behavior.
  3. TTL Overrides

    • Global TTL in config overrides method-level TTLs. Set explicitly if needed:
      ttl: 300  # Overrides all methods
      
  4. Varnish Server Sync

    • The bundle assumes Varnish is configured to purge via HTTP PURGE requests. Verify your Varnish instance supports:
      vcl_recv {
          if (req.method == "PURGE") {
              return (purge);
          }
      }
      

Debugging

  • Enable Logging Add to config/packages/donkecode_varnish.yaml:

    debug: true
    

    Logs appear in var/log/dev.log (or prod.log).

  • Check Cache Keys Use the debug:varnish command:

    php bin/console debug:varnish
    

    Lists all cached keys and their metadata.

Extension Points

  1. Custom Cache Providers Implement DonkeCode\VarnishBundle\Cache\CacheProviderInterface for alternative backends (e.g., Redis):

    class RedisVarnishProvider implements CacheProviderInterface
    {
        public function get($key) { /* ... */ }
        public function set($key, $value, $ttl) { /* ... */ }
        public function purge($key) { /* ... */ }
    }
    

    Register in services.yaml:

    services:
        DonkeCode\VarnishBundle\Cache\VarnishCache:
            arguments:
                $provider: '@app.redis_varnish_provider'
    
  2. Conditional Logic Extend DonkeCode\VarnishBundle\Cache\CacheKeyGenerator to add custom rules:

    public function generateKey(Request $request, UserInterface $user = null)
    {
        $key = parent::generateKey($request, $user);
        if ($user && $user->hasRole('FEATURE_X')) {
            $key .= '_feature_x';
        }
        return $key;
    }
    
  3. Varnish Purge Events Listen for varnish.purge events to trigger external actions:

    use DonkeCode\VarnishBundle\Event\PurgeEvent;
    
    public function onPurge(PurgeEvent $event)
    {
        // Notify analytics, log purge, etc.
    }
    
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.
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
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