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

Sulu Http Cache Bundle Laravel Package

alengo/sulu-http-cache-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require alengo/sulu-http-cache-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Alengo\SuluHttpCacheBundle\SuluHttpCacheBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config (if needed):

    php bin/console sulu:http-cache:install
    

    Override defaults in config/packages/sulu_http_cache.yaml:

    sulu_http_cache:
        tracking_params: ['utm_source', 'utm_medium', 'utm_campaign']  # Customize as needed
        cookie_prefix: 'cta_'  # Prefix for marketing cookies
    
  3. First Use Case Cache-Breaking Query Parameters Strip tracking params from cached responses:

    use Alengo\SuluHttpCacheBundle\Cache\CacheAwareRequest;
    
    $request = new CacheAwareRequest($originalRequest);
    $cleanUrl = $request->getUri(); // Automatically strips tracking params
    

    Marketing Cookie Handling Store attribution cookies at the reverse-proxy layer:

    $this->get('sulu_http_cache.cookie_handler')->storeCookie(
        'cta_campaign_id',
        'summer_sale',
        ['lifetime' => 3600]
    );
    

Implementation Patterns

1. Request Sanitization

Workflow:

  • Use CacheAwareRequest to clean URLs before caching.
  • Integrate with Symfony’s RequestStack for global access:
    $request = $this->get('request_stack')->getCurrentRequest();
    $cleanRequest = new CacheAwareRequest($request);
    

Symfony Event Integration Listen to kernel.request to auto-sanitize requests:

use Alengo\SuluHttpCacheBundle\EventListener\CacheAwareRequestListener;

services:
    Alengo\SuluHttpCacheBundle\EventListener\CacheAwareRequestListener:
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

2. Cookie Management

Reverse-Proxy Layer Handling

  • Store marketing cookies (e.g., cta_campaign_id) in the SuluHttpCacheBundle config.
  • Use the CookieHandler service to manage cookies:
    $this->get('sulu_http_cache.cookie_handler')->setCookie(
        'cta_source',
        'facebook',
        ['path' => '/', 'secure' => true]
    );
    

Dynamic Cookie Storage

  • Extend the CookieHandler to support custom storage backends (e.g., Redis):
    sulu_http_cache:
        cookie_storage: 'redis://localhost:6379/0'
    

3. Cache Key Generation

Custom Cache Keys Override the default cache key logic in a subscriber:

use Alengo\SuluHttpCacheBundle\Event\CacheKeyEvent;

public function onGenerateCacheKey(CacheKeyEvent $event) {
    $event->setKey(md5($event->getRequest()->getPathInfo() . $event->getTrackingParams()));
}

Symfony Cache Integration Use the bundle’s cache key with Symfony’s HttpCache:

use Alengo\SuluHttpCacheBundle\Cache\CacheKeyGenerator;

$generator = new CacheKeyGenerator($this->getParameter('sulu_http_cache.tracking_params'));
$cacheKey = $generator->generate($request);

4. Reverse-Proxy Integration

Varnish/Nginx Configuration Configure your reverse proxy to respect the X-Sulu-Cache-Key header:

location / {
    set $cache_key $request_uri;
    if ($http_x_sulu_cache_key) {
        set $cache_key $http_x_sulu_cache_key;
    }
    proxy_cache_key "$cache_key";
}

Header-Based Cache Control Add cache headers dynamically:

use Alengo\SuluHttpCacheBundle\Response\CacheResponse;

$response = new CacheResponse($content, 200, [
    'Cache-Control' => 'public, max-age=3600',
]);

Gotchas and Tips

Pitfalls

  1. Tracking Param Whitelisting

    • Issue: Forgetting to whitelist new tracking params in sulu_http_cache.tracking_params can cause cache misses.
    • Fix: Use a wildcard (*) cautiously—validate params server-side first.
  2. Cookie Scope Conflicts

    • Issue: Overlapping cookie names (e.g., cta_* vs. existing cookies) may cause conflicts.
    • Fix: Use a unique cookie_prefix and audit existing cookies.
  3. Reverse-Proxy Mismatch

    • Issue: If the reverse proxy ignores X-Sulu-Cache-Key, cached responses will use raw URLs.
    • Fix: Test proxy config with curl -H "X-Sulu-Cache-Key: test" and verify headers.
  4. Dynamic Content Leaks

    • Issue: Personalized content (e.g., user-specific data) may leak into cached responses.
    • Fix: Exclude dynamic routes from caching or use Vary: Cookie headers.

Debugging

  • Log Cache Keys Enable debug mode to log generated cache keys:

    sulu_http_cache:
        debug: true
    

    Check logs for SULU_HTTP_CACHE_KEY entries.

  • Validate Cookie Storage Use bin/console debug:container sulu_http_cache.cookie_handler to inspect stored cookies.

Extension Points

  1. Custom Cache Key Logic Extend CacheKeyGenerator to support:

    • User-agent-based keys.
    • Geographic targeting (e.g., ?locale=fr).
  2. Cookie Storage Backends Implement Alengo\SuluHttpCacheBundle\Cookie\CookieStorageInterface for:

    • Database storage.
    • Distributed cache (Redis, Memcached).
  3. Event-Driven Extensions Subscribe to sulu_http_cache.cache_key_generated to modify keys pre-caching:

    use Alengo\SuluHttpCacheBundle\Event\CacheKeyEvent;
    
    public function onCacheKeyGenerated(CacheKeyEvent $event) {
        if ($event->getRequest()->getPathInfo() === '/promo') {
            $event->setKey('promo_' . $event->getKey());
        }
    }
    

Performance Tips

  • Batch Cookie Operations Use CookieHandler::flush() to clear stale cookies in bulk during migrations.
  • Edge Caching Configure CDN (Cloudflare, Fastly) to cache based on X-Sulu-Cache-Key headers.
  • Avoid Over-Caching Exclude API endpoints or admin routes from cache:
    sulu_http_cache:
        excluded_paths:
            - ^/api/
            - ^/_admin/
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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