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

desarrolla2/cache

Immutable PSR-16 simple cache library for PHP with multiple adapters (APCu, File, Memcached, Redis, MongoDB, etc.) plus a Chain adapter. Supports configurable options like default TTL via withOption/withOptions. Aims to be complete, correct, and fast.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require desarrolla2/cache
    

    No service provider registration is required (PSR-16 compliant).

  2. Basic Usage: Cache a value for 10 minutes using the PSR-16 interface:

    use Desarrolla2\Cache\Cache;
    
    $cache = new Cache();
    $cache->set('key', 'value', 600); // 600 seconds (10 minutes)
    $value = $cache->get('key');
    
  3. First Use Case: Use immutable CacheItem for advanced operations:

    $item = $cache->getItem('key');
    if (!$item->isHit()) {
        $item->set('value')->expiresAfter(600); // 600 seconds (10 minutes)
        $cache->save($item);
    }
    $value = $item->get();
    

Implementation Patterns

PSR-16 Compliance

  • Standard Interface: Leverage PSR-16 methods (get(), set(), delete(), clear(), getMultiple(), setMultiple()).
  • Immutable Items: Use CacheItem for deferred expiration and conditional logic:
    $item = $cache->getItem('user:1');
    if (!$item->isHit()) {
        $item->set($userData)->expiresAfter(3600); // 3600 seconds (1 hour)
        $cache->save($item);
    }
    

Adapter Integration

  • PSR-16 Adapters: Integrate with any PSR-16-compliant storage (e.g., league/redis-cache, predis/predis):
    use League\Cache\FileCache;
    
    $cache = new Cache(new FileCache(storage_path('framework/cache')));
    
  • Fallback Adapters: Chain adapters for resilience:
    $primary = new Cache(new RedisCache());
    $fallback = new Cache(new FileCache());
    $cache = new FallbackCache([$primary, $fallback]);
    

Workflows

  1. Cache-aside Pattern:

    $cache = new Cache();
    $data = $cache->get('expensive_data');
    if ($data === null) {
        $data = fetchExpensiveData();
        $cache->set('expensive_data', $data, 3600); // 3600 seconds (1 hour)
    }
    
  2. Tagging via Keys: Use consistent prefixes for logical grouping (e.g., users:*):

    $cache->set('users:1', $user, 3600); // 3600 seconds (1 hour)
    $cache->deleteMultiple(['users:1', 'users:2']);
    
  3. Deferred Expiration with Immutable Items:

    $item = $cache->getItem('config');
    $item->set($config)->expiresAfter(3600); // 3600 seconds (1 hour)
    $cache->save($item);
    

Integration Tips

  • Manual Laravel Binding: Since this is a PSR-16-only package, bind it to Laravel's container manually:

    $app->bind('cache.store', function ($app) {
        return new Cache(new RedisCache());
    });
    

    Then inject it via dependency injection:

    public function __construct(CacheInterface $cache) {
        $this->cache = $cache;
    }
    
  • Testing: Mock CacheInterface for unit tests:

    $mockCache = $this->createMock(CacheInterface::class);
    $mockCache->method('get')->willReturn('mocked');
    $cache = new Cache($mockCache);
    

Gotchas and Tips

Pitfalls

  1. Breaking Changes in v3.0.0:

    • No Laravel Facade: Direct Cache facade usage is not supported. Use PSR-16 methods directly or manually bind the package to Laravel's container.
    • TTL in Seconds: All time-to-live (TTL) values must be in seconds (not minutes as in previous versions).
    • Pure PSR-16: This is a strict PSR-16 implementation—no Laravel-specific helpers (e.g., remember(), forever()). Use PSR-16 methods exclusively.
    • Immutable Items: CacheItem objects are immutable. To update, fetch a new item or re-create it.
  2. Adapter Limitations:

    • No Built-in Tagging: Implement custom key patterns (e.g., tags:user:1) or use a wrapper like taggable-cache.
    • No Locking: Use external tools (e.g., php-lock) for distributed locks.
  3. Serialization:

    • PSR-16 requires strict serialization. Avoid non-serializable objects:
      $cache->set('key', json_encode($data)); // Ensure data is serializable
      

Debugging

  • Log Cache Operations: Use a decorator pattern to log cache hits/misses:

    $cache = new Cache(new LoggingCache(new RedisCache(), new MonologLogger()));
    
  • Check Adapter Health:

    if (!$cache->getItem('health_check')->isHit()) {
        Log::error('Cache adapter is unresponsive!');
    }
    

Extension Points

  1. Custom CacheItem: Extend CacheItem for domain-specific logic:

    class UserCacheItem extends CacheItem {
        public function setUser(User $user) {
            $this->set($user->toArray());
        }
    }
    
  2. Decorator Pattern: Wrap the cache for cross-cutting concerns (e.g., logging, metrics):

    class MetricsCache implements CacheInterface {
        protected $cache;
    
        public function __construct(CacheInterface $cache) {
            $this->cache = $cache;
        }
    
        public function get($key) {
            $start = microtime(true);
            $result = $this->cache->get($key);
            $this->recordMetric($key, microtime(true) - $start);
            return $result;
        }
        // Delegate other methods
    }
    
  3. PSR-16 Middleware: Chain middleware for pre/post-processing:

    $cache = new Cache(
        new MiddlewareCache(
            new RedisCache(),
            [new CompressionMiddleware(), new ValidationMiddleware()]
        )
    );
    
  4. Environment-Specific Adapters:

    $cache = new Cache(
        env('CACHE_DRIVER') === 'redis'
            ? new RedisCache()
            : new FileCache()
    );
    
  5. Laravel Integration (Manual): Since this package is PSR-16-only, manually bind it to Laravel's container:

    $app->bind('cache.store', function ($app) {
        return new Cache(new RedisCache());
    });
    

    Then use it via dependency injection:

    public function __construct(CacheInterface $cache) {
        $this->cache = $cache;
    }
    
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
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
spatie/mailcoach-vapor