Weave 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

Cache Bundle Laravel Package

sonata-project/cache-bundle

Symfony bundle providing caching services for Sonata projects, with pluggable cache backends and integration helpers. Note: this repository is abandoned and no longer actively maintained; community help welcome.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sonata-project/cache-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Sonata\CacheBundle\SonataCacheBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration: Configure cache adapters in config/packages/sonata_cache.yaml:

    sonata_cache:
        app:
            driver: cache.app
            namespace: sonata.cache
            default_lifetime: 3600
        cache:
            driver: cache.array
    
  3. First Use Case: Inject CacheManagerInterface into a service/controller:

    use Sonata\Cache\CacheManagerInterface;
    
    class MyController extends AbstractController
    {
        public function __construct(private CacheManagerInterface $cacheManager) {}
    
        public function index()
        {
            $cache = $this->cacheManager->getCache('app');
            $data = $cache->get('my_key') ?? 'default_value';
            return $this->json($data);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Cache Retrieval/Storage:

    // Store
    $cache->set('key', $value, 3600); // 1-hour TTL
    
    // Retrieve
    $value = $cache->get('key');
    
    // Delete
    $cache->delete('key');
    
  2. Tag-Based Invalidation:

    # config/packages/sonata_cache.yaml
    sonata_cache:
        app:
            driver: cache.app
            tags: ['my_tag']
    
    $cache->invalidateTags(['my_tag']); // Invalidate all keys with this tag
    
  3. Doctrine Integration:

    # config/packages/sonata_cache.yaml
    sonata_cache:
        doctrine:
            metadata_cache_driver: cache.app
            query_cache_driver: cache.app
            result_cache_driver: cache.app
    
  4. SSI/ESI Caching:

    {# ESI Example #}
    {% cache 'esi_key' %}
        {% render url('path/to/controller') %}
    {% endcache %}
    

Integration Tips

  • Symfony Cache: Use cache:clear commands via CLI:
    php bin/console sonata:cache:flush-all
    
  • Custom Cache Pools: Extend CacheManager for multi-tenant apps:
    class TenantCacheManager extends CacheManager
    {
        public function getCache(string $name, string $tenantId): CacheInterface
        {
            return $this->getCache($tenantId . '.' . $name);
        }
    }
    
  • Event Listeners: Subscribe to cache events:
    use Sonata\CacheBundle\Event\CacheEvent;
    
    class MyCacheListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                CacheEvent::INVALIDATE => 'onCacheInvalidate',
            ];
        }
    
        public function onCacheInvalidate(CacheEvent $event): void
        {
            // Handle invalidation logic
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Classes:

    • Avoid Sonata\CacheBundle\* classes; use Sonata\Cache\* instead (e.g., CacheManager → Sonata\Cache\CacheManager).
    • Fix: Update imports and service references in config/services.yaml.
  2. Command Registration:

    • Commands like sonata:cache:flush may fail if not properly autowired.
    • Fix: Ensure Sonata\CacheBundle\Command\* classes are loaded via autowiring or explicit service definitions.
  3. PHP/Symfony Version Mismatch:

    • Bundle supports PHP 7.3+ and Symfony 5.2+ (as of v3.4.0).
    • Fix: Downgrade or upgrade dependencies if using older versions.
  4. Twig Integration:

    • Twig usage is optional but requires explicit configuration:
      sonata_cache:
          twig:
              enabled: true
      
  5. Cache Invalidation Race Conditions:

    • Tag-based invalidation may not be immediate due to distributed cache backends (e.g., Redis).
    • Fix: Use invalidateTags() in a transactional context or add retry logic.

Debugging Tips

  • Check Cache Backend:
    php bin/console debug:cache
    
  • Log Cache Hits/Misses: Enable debug mode and inspect CacheEvent::MISS/CacheEvent::HIT events.

Extension Points

  1. Custom Cache Drivers: Implement Sonata\Cache\CacheInterface and register via:

    services:
        my.custom_cache:
            class: App\Cache\MyCustomCache
            tags: ['sonata.cache.driver']
    
  2. Override Default Services:

    # config/services.yaml
    Sonata\Cache\CacheManager: '@app.custom_cache_manager'
    
  3. Extend CacheManager:

    class CustomCacheManager extends CacheManager
    {
        public function getCache(string $name): CacheInterface
        {
            if ($name === 'special') {
                return $this->getCache('app'); // Fallback logic
            }
            return parent::getCache($name);
        }
    }
    

Configuration Quirks

  • Namespace Collisions: Ensure namespace in sonata_cache.yaml is unique per environment (e.g., dev.sonata.cache).
  • Redis/Predis: Configure password/auth in sonata_cache.yaml:
    sonata_cache:
        redis:
            driver: predis
            host: 127.0.0.1
            password: 'your_password'
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast