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

fig/cache-util

Utilities for building PSR-6 cache libraries: traits and base classes that handle common boilerplate for cache pools and items. Includes a simple in-memory PSR-6 implementation for demos and debugging (not production-ready).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require php-fig/cache-util
    

    Add to composer.json:

    "require": {
        "php-fig/cache-util": "^1.0"
    }
    
  2. First Use Case: Leverage the in-memory demo for testing or debugging:

    use FIG\Cache\CacheItemPoolInterface;
    use FIG\Cache\SimpleCache;
    
    $cache = new SimpleCache(); // Built-in in-memory PSR-6 cache
    $cache->set('key', 'value', 60); // Set with TTL
    $value = $cache->get('key'); // Retrieve value
    
  3. Where to Look First:

    • Traits: CacheItemPoolTrait, CacheItemInterface in src/Traits/.
    • Demo: SimpleCache class in src/SimpleCache.php for quick experimentation.
    • PSR-6 Docs: PSR-6 Specification for method signatures.

Implementation Patterns

1. Trait-Based PSR-6 Compliance

Use traits to scaffold custom cache pools (e.g., for Redis, S3, or database backends):

use FIG\Cache\Traits\CacheItemPoolTrait;
use FIG\Cache\CacheItemInterface;

class CustomCache implements CacheItemPoolInterface {
    use CacheItemPoolTrait;

    // Implement required methods (e.g., getItem(), save(), delete())
    public function getItem($key) {
        return new CacheItem($this->fetchFromBackend($key), $this);
    }

    // Delegate PSR-6 logic to the trait
}

2. Cache Item Standardization

Extend CacheItem for consistent metadata handling (e.g., tags, expiration):

use FIG\Cache\CacheItem;

class TaggedCacheItem extends CacheItem {
    public function setTag($tag) {
        $this->metadata['_tags'][] = $tag;
    }
}

3. Hybrid Caching Strategies

Combine with Laravel’s Cache facade for layered caching:

use Illuminate\Support\Facades\Cache;
use FIG\Cache\CacheItemPoolInterface;

class HybridCache implements CacheItemPoolInterface {
    private $primaryCache;
    private $fallbackCache;

    public function __construct() {
        $this->primaryCache = Cache::store('redis');
        $this->fallbackCache = new SimpleCache(); // In-memory fallback
    }

    public function getItem($key) {
        try {
            return $this->primaryCache->getItem($key);
        } catch (\Exception $e) {
            return $this->fallbackCache->getItem($key);
        }
    }
}

4. Testing Utilities

Use SimpleCache for unit tests (no external dependencies):

use FIG\Cache\SimpleCache;

public function testCacheLogic() {
    $cache = new SimpleCache();
    $cache->set('test', 'data', 300);
    $this->assertEquals('data', $cache->get('test'));
}

5. Laravel Service Provider Integration

Bind custom cache pools to Laravel’s container:

use Illuminate\Support\ServiceProvider;
use FIG\Cache\CacheItemPoolInterface;

class CacheServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->bind(CacheItemPoolInterface::class, function ($app) {
            return new CustomCache(); // Your PSR-6-compliant cache
        });
    }
}

Gotchas and Tips

Pitfalls

  1. Not Production-Ready:

    • SimpleCache is in-memory only—avoid using it in production.
    • Pair with Predis, Doctrine Cache, or Laravel’s FileCache for real deployments.
  2. Trait Method Conflicts:

    • Override trait methods explicitly if extending a class that already implements CacheItemPoolInterface:
      class MyCache extends BaseCache implements CacheItemPoolInterface {
          use CacheItemPoolTrait {
              getItem as traitGetItem; // Avoid conflicts
          }
      }
      
  3. Metadata Handling:

    • PSR-6 metadata is string-based (e.g., array serialized to JSON). Validate serialization/deserialization:
      $item->setMetadata('tags', ['user', 'admin']);
      $tags = json_decode($item->getMetadata()['tags'], true);
      
  4. TTL Granularity:

    • TTLs are seconds (not milliseconds). Ensure your backend converts correctly:
      $cache->set('key', 'value', 60); // 60 seconds
      

Debugging Tips

  1. Log Cache Operations: Decorate CacheItemPoolInterface to log calls:

    class LoggingCache implements CacheItemPoolInterface {
        private $delegate;
    
        public function __construct(CacheItemPoolInterface $delegate) {
            $this->delegate = $delegate;
        }
    
        public function getItem($key) {
            \Log::debug("Cache get: {$key}");
            return $this->delegate->getItem($key);
        }
    
        // Delegate other methods...
    }
    
  2. Validate PSR-6 Compliance: Use PHP-CS-Fixer with PSR-6 rules or a custom script to verify implementations.

  3. In-Memory Cache Limits: SimpleCache does not persist between requests. Use for short-lived tests only.

Extension Points

  1. Custom Cache Items: Extend CacheItem to add domain-specific metadata:

    class UserCacheItem extends CacheItem {
        public function setUserId($id) {
            $this->metadata['user_id'] = $id;
        }
    }
    
  2. Cache Pool Decorators: Wrap existing caches to add features (e.g., logging, analytics):

    class AnalyticsCache implements CacheItemPoolInterface {
        private $cache;
    
        public function __construct(CacheItemPoolInterface $cache) {
            $this->cache = $cache;
        }
    
        public function getItem($key) {
            $item = $this->cache->getItem($key);
            \Analytics::track('cache_hit', ['key' => $key]);
            return $item;
        }
    }
    
  3. Laravel-Specific Extensions: Create a Laravel package to bridge fig/cache-util with Laravel’s Cache facade:

    // Example: CacheItemPool facade binding
    Cache::extend('custom', function () {
        return new CustomCache(); // Uses fig/cache-util traits
    });
    

Configuration Quirks

  1. No Built-in Config: The package is zero-config. All behavior is code-driven.

  2. Laravel Cache Drivers: If using Laravel’s Cache facade, ensure your custom driver implements CacheItemPoolInterface:

    Cache::extend('s3', function ($app) {
        return new S3Cache(); // Must implement PSR-6
    });
    
  3. PHP Version: Requires PHP 7.4+. Test on Laravel 8+ for compatibility.

Performance Considerations

  • Trait Overhead: Minimal (~5–10ms per operation). Benchmark in your stack.
  • In-Memory Demo: Not for production. Use only for testing/debugging.
  • Serialization: Avoid large metadata—PSR-6 metadata is string-based (JSON-serialized).
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.
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
spatie/mailcoach-vapor