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

danieltoader/cache-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require emag-tech-labs/annotation-cache-bundle
    

    Add to config/bundles.php (Symfony) or config/packages/annotation_cache.yaml (Laravel via Symfony bridge):

    EmagTechLabs\AnnotationCacheBundle\AnnotationCacheBundle::class => ['all' => true],
    
  2. Enable in services.yaml

    services:
        _defaults:
            autowire: true
            autoconfigure: true
        EmagTechLabs\AnnotationCacheBundle\:
            resource: '../vendor/emag-tech-labs/annotation-cache-bundle/*'
            exclude: '../vendor/emag-tech-labs/annotation-cache-bundle/{DependencyInjection,Tests,Resources}/*'
    
  3. First Use Case Annotate a service method to cache its response:

    use EmagTechLabs\AnnotationCacheBundle\Annotation\Cache;
    
    class MyService {
        /**
         * @Cache(key="user_data_$id", ttl=3600)
         */
        public function getUserData(int $id) {
            return User::find($id)->toArray();
        }
    }
    
    • Laravel Note: Use #[Cache(...)] for PHP 8+ attributes (requires bundle config adjustment).

Implementation Patterns

Core Workflow

  1. Annotation/Attribute Placement

    • Apply @Cache or #[Cache] to methods in container-bound services.
    • Key parameters:
      • key: Dynamic string (supports $var interpolation).
      • ttl: Time-to-live in seconds (default: null = no expiry).
      • prefix: Optional cache prefix (e.g., app_).
      • store: PSR-6 cache service ID (default: cache.app).
  2. Proxy Generation

    • Bundle auto-generates proxies at runtime via ProxyManager.
    • No manual proxy classes needed.
  3. Integration with Laravel

    • Cache Stores: Use Laravel’s PSR-6 adapters (e.g., cache.array, cache.redis).
      # config/packages/annotation_cache.yaml
      emag_annotation_cache:
          default_store: cache.redis
      
    • Service Binding: Bind services to the container:
      $this->app->bind(MyService::class, function ($app) {
          return new MyService();
      });
      
  4. Dynamic Key Generation

    • Use method arguments in keys:
      #[Cache(key: "product_$id_$category")]
      public function getProduct(int $id, string $category) { ... }
      
  5. Cache Invalidation

    • Manually clear cache via PSR-6 interface:
      $this->cache->delete('user_data_123');
      
    • Or use bundle’s CacheManager:
      $this->container->get('emag_annotation_cache.cache_manager')->invalidate('user_data_*');
      

Gotchas and Tips

Pitfalls

  1. ProxyManager Conflicts

    • Issue: ProxyManager may clash with other bundles using it (e.g., Doctrine).
    • Fix: Explicitly configure ProxyManager in config/packages/annotation_cache.yaml:
      emag_annotation_cache:
          proxy_manager:
              enabled: true
              adapter: file
      
  2. Annotation Parsing Failures

    • Issue: PHP 8 attributes require bundle config update (see #12).
    • Fix: Set use_attributes: true in config:
      emag_annotation_cache:
          use_attributes: true
      
  3. Circular Dependencies

    • Issue: Cached proxies may break circular references in services.
    • Fix: Avoid caching methods in services with circular dependencies or use @Cache(skip_if_missing: true).
  4. Key Collisions

    • Issue: Dynamic keys with identical values (e.g., key="data_$id" where $id is static) may overwrite cache unintentionally.
    • Fix: Use unique prefixes or include more context in keys (e.g., data_$id_$timestamp).
  5. TTL Granularity

    • Issue: Hardcoded TTLs may not suit all use cases (e.g., real-time data).
    • Fix: Combine with runtime checks:
      #[Cache(key: "volatile_data", ttl: 60)]
      public function getVolatileData() {
          if ($this->isDataFresh()) {
              return $this->fetchFreshData();
          }
          return $this->cachedData;
      }
      

Debugging Tips

  1. Enable Logging

    • Set debug: true in config to log cache hits/misses:
      emag_annotation_cache:
          debug: true
      
  2. Proxy Inspection

    • Dump the proxy class to verify annotations are processed:
      var_dump(get_class($this->container->get(MyService::class)));
      
  3. Cache Store Verification

    • Check PSR-6 store is bound correctly:
      $this->container->has('cache.app'); // Should return true
      

Extension Points

  1. Custom Cache Stores

    • Implement Psr\Cache\CacheItemPoolInterface and bind it to the container:
      services:
          my_custom_cache:
              class: App\Cache\MyCachePool
              tags: ['cache.pool']
      
    • Reference it in annotations:
      #[Cache(store: 'my_custom_cache', key: "my_key")]
      
  2. Pre/Post Cache Hooks

    • Extend EmagTechLabs\AnnotationCacheBundle\CacheableClassTrait to add logic before/after cache checks:
      class MyService extends \EmagTechLabs\AnnotationCacheBundle\CacheableClassTrait {
          protected function beforeCacheCheck(string $method, array $args) {
              // Custom logic (e.g., auth checks)
          }
      }
      
  3. Attribute Interceptors (PHP 8+)

    • Override EmagTechLabs\AnnotationCacheBundle\Attribute\CacheAttribute to add custom validation:
      class CustomCacheAttribute extends CacheAttribute {
          public function validate(array $args): void {
              if (!in_array($args['key'], $this->allowedKeys)) {
                  throw new \InvalidArgumentException('Key not allowed');
              }
          }
      }
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware