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

Doctrine Cache Bundle Laravel Package

effiana/doctrine-cache-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation (if still needed for legacy projects):

    composer require effiana/doctrine-cache-bundle
    

    Note: For Symfony 5+, skip this and configure Doctrine Cache manually via doctrine/cache package.

  2. Enable the Bundle (Symfony <5 only): Add to config/bundles.php:

    return [
        // ...
        Effiana\DoctrineCacheBundle\EffianaDoctrineCacheBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Configure a Doctrine cache driver (e.g., APCu) in config/packages/doctrine_cache.yaml:

    doctrine_cache:
        providers:
            my_provider:
                type: apcu
                namespace: my_app_
    

    Then use it in a repository:

    use Doctrine\ORM\EntityRepository;
    
    class MyEntityRepository extends EntityRepository
    {
        public function findCached($id)
        {
            $cache = $this->getEntityManager()->getCache();
            $cacheKey = 'my_entity_' . $id;
    
            if (!$cache->contains($cacheKey)) {
                $entity = $this->find($id);
                $cache->save($cacheKey, $entity);
            } else {
                $entity = $cache->fetch($cacheKey);
            }
            return $entity;
        }
    }
    

Implementation Patterns

Common Workflows

  1. Query Result Caching: Cache entire query results (e.g., lists) to avoid repeated DB hits:

    $cacheKey = 'all_users_' . $roleId;
    if (!$cache->contains($cacheKey)) {
        $users = $this->createQueryBuilder('u')
            ->where('u.role = :role')
            ->setParameter('role', $roleId)
            ->getQuery()
            ->getResult();
        $cache->save($cacheKey, $users, 3600); // Cache for 1 hour
    } else {
        $users = $cache->fetch($cacheKey);
    }
    
  2. Entity Metadata Caching: Leverage Doctrine’s built-in cache for metadata (e.g., metadata_cache provider):

    doctrine_cache:
        providers:
            metadata_cache:
                type: file
                namespace: doctrine_metadata_
                file: "%kernel.cache_dir%/doctrine/metadata"
    
  3. Integration with Symfony Cache: Bridge Doctrine Cache with Symfony’s CacheInterface (for Symfony 5+):

    use Doctrine\Common\Cache\CacheProvider;
    use Symfony\Component\Cache\Adapter\AdapterInterface;
    
    $doctrineCache = new CacheProvider();
    $symfonyCache = new AdapterInterface($doctrineCache);
    

Best Practices

  • Namespace Isolation: Use unique namespaces (e.g., app_) to avoid key collisions.
  • TTL Management: Set appropriate TTLs (e.g., shorter for volatile data, longer for static configs).
  • Cache Invalidation: Clear cache manually or via events (e.g., postPersist, postRemove):
    $this->getEntityManager()->getCache()->delete('my_entity_' . $id);
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

    • The bundle is unmaintained for Symfony 5+. Migrate to manual configuration or use symfony/cache.
    • Example manual setup (Symfony 5+):
      # config/packages/doctrine.yaml
      doctrine:
          orm:
              metadata_cache_driver: apcu
              query_cache_driver: apcu
              result_cache_driver: apcu
      
  2. Cache Provider Quirks:

    • APCu: Requires php-apcu extension. Fails silently if disabled.
    • File Cache: Slow for high-traffic apps; avoid in shared hosting.
    • Redis/Memcached: Needs doctrine/cache + predis/php-memcached extensions.
  3. Key Collisions:

    • Default namespace (doctrine_) may clash with other bundles. Always specify a custom namespace.
  4. Serialization Issues:

    • Doctrine Cache serializes data. Complex objects (e.g., with closures) may fail. Use __serialize()/__unserialize() or avoid caching them.

Debugging Tips

  • Check Cache Contents:
    var_dump($cache->getStats()); // For APCu/File
    
  • Enable Logging:
    doctrine_cache:
        providers:
            my_provider:
                type: apcu
                namespace: my_app_
                logging: true # Logs cache hits/misses
    
  • Clear Cache Programmatically:
    $cache->deleteAll(); // Clears all keys in namespace
    

Extension Points

  1. Custom Cache Providers: Extend Doctrine\Common\Cache\CacheProvider for bespoke storage (e.g., database):

    class DbCacheProvider extends CacheProvider {
        public function fetch($id) { /* Query DB */ }
        public function save($id, $data, $lifeTime = 0) { /* Save to DB */ }
    }
    

    Register in services.yaml:

    services:
        App\Cache\DbCacheProvider:
            tags: ['doctrine.cache_provider']
    
  2. Event Listeners: Invalidate cache on entity changes:

    use Doctrine\ORM\Event\LifecycleEventArgs;
    
    class CacheInvalidator {
        public function postRemove(LifecycleEventArgs $args) {
            $entity = $args->getEntity();
            $cache = $args->getEntityManager()->getCache();
            $cache->delete('entity_' . spl_object_hash($entity));
        }
    }
    

    Register as a service with tags: ['doctrine.event_listener'].

  3. Symfony Cache Adapter: For Symfony 5+, wrap Doctrine Cache in a Symfony CacheInterface:

    use Symfony\Component\Cache\Adapter\DoctrineProviderAdapter;
    
    $doctrineCache = new \Doctrine\Common\Cache\ApcuCache();
    $symfonyCache = new DoctrineProviderAdapter($doctrineCache);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui