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

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., CacheManagerSonata\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.
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