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 Laravel Package

becklyn/cache

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require becklyn/cache
    

    Ensure Becklyn\CacheBundle\BecklynCacheBundle::class is registered in config/bundles.php.

  2. First Use Case: Inject SimpleCacheFactory into a service and fetch a cached item with a fallback generator:

    use Becklyn\Cache\Cache\SimpleCacheFactory;
    
    class MyService {
        public function __construct(private SimpleCacheFactory $cacheFactory) {}
    
        public function getCachedData() {
            return $this->cacheFactory->getItem(
                "my.key",
                fn() => $this->expensiveOperation()
            )->get();
        }
    }
    
  3. Key Locations:

    • Factory: SimpleCacheFactory (entry point for cache operations).
    • Configuration: config/packages/becklyn_cache.yaml (if extended).
    • Documentation: README’s "Usage" and "Caching Based on Symfony Config" sections.

Implementation Patterns

Core Workflows

  1. Lazy-Loading with Fallback:

    $cacheItem = $cacheFactory->getItem("key", fn() => $this->fetchFromDB());
    $data = $cacheItem->get(); // Calls fallback if cache misses
    
  2. Config-Driven Invalidation: Use Symfony’s ResourceInterface for cache invalidation (e.g., config files, routes):

    $cacheItem = $cacheFactory->getItem(
        "config.cache",
        fn() => $this->loadConfig(),
        [new \Symfony\Component\Config\Resource\FileResource('/path/to/config.yaml')]
    );
    
  3. Two-Level Caching:

    • Level 1: Fast in-memory cache (Symfony’s CacheInterface).
    • Level 2: ConfigCache for invalidation (triggered by tracked resources).
  4. Integration with Laravel:

    • Bind SimpleCacheFactory to Laravel’s container in AppServiceProvider:
      $this->app->bind(SimpleCacheFactory::class, function ($app) {
          return new SimpleCacheFactory($app['cache']);
      });
      

Best Practices

  • Key Naming: Use namespaced keys (e.g., app.feature.data) to avoid collisions.
  • TTL Management: Set explicit TTLs for volatile data:
    $cacheItem->expiresAfter(3600); // 1 hour
    
  • Bulk Operations: Use SimpleCacheFactory::getMultiple() for batch fetching:
    $items = $cacheFactory->getMultiple([
        "key1" => fn() => $data1,
        "key2" => fn() => $data2,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Concurrency Warning:

    • The bundle lacks stampede protection. For high-traffic apps:
      • Pre-warm cache with @cache tags.
      • Fall back to Symfony’s Cache component for critical sections.
  2. Resource Tracking:

    • Incorrect ResourceInterface implementations may break invalidation. Test with:
      $resource = new \Symfony\Component\Config\Resource\FileResource('/nonexistent');
      $cacheItem = $cacheFactory->getItem("test", fn() => [], [$resource]);
      $cacheItem->invalidate(); // Verify invalidation works.
      
  3. Serialization Issues:

    • Non-serializable objects (e.g., closures, resources) will fail. Use serialize()/unserialize() or JSON encoding for complex data.
  4. Laravel-Specific Quirks:

    • Laravel’s Cache facade may not support all CacheInterface methods. Use CacheManager for compatibility:
      $cache = app('cache')->driver('array'); // or 'file', 'redis'
      

Debugging Tips

  • Cache Misses: Enable Symfony’s cache debug:
    $cacheFactory->getItem("key")->isHit(); // Check if cached.
    
  • Invalidation: Log resource changes to trace invalidation:
    $cacheItem->invalidate(); // Add logging before/after.
    
  • Performance: Profile with microtime() to compare against Laravel’s Cache::remember():
    $start = microtime(true);
    $data = $cacheItem->get();
    echo "Time: " . (microtime(true) - $start);
    

Extension Points

  1. Custom Cache Drivers: Extend SimpleCacheFactory to support Laravel’s Cache drivers:

    class LaravelCacheFactory extends SimpleCacheFactory {
        public function __construct(\Illuminate\Contracts\Cache\Store $cache) {
            parent::__construct($cache);
        }
    }
    
  2. Event Listeners: Hook into CacheItemInvalidatedEvent (if extended) to sync external caches:

    // Hypothetical extension
    $cacheItem->onInvalidate(function () {
        Cache::forget('external_key');
    });
    
  3. Config Overrides: Override default TTLs in config/packages/becklyn_cache.yaml:

    becklyn_cache:
        default_ttl: 7200 # 2 hours
        stale_ttl: 300   # 5 minutes
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony