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).
Installation:
composer require php-fig/cache-util
Add to composer.json:
"require": {
"php-fig/cache-util": "^1.0"
}
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
Where to Look First:
CacheItemPoolTrait, CacheItemInterface in src/Traits/.SimpleCache class in src/SimpleCache.php for quick experimentation.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
}
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;
}
}
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);
}
}
}
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'));
}
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
});
}
}
Not Production-Ready:
SimpleCache is in-memory only—avoid using it in production.FileCache for real deployments.Trait Method Conflicts:
CacheItemPoolInterface:
class MyCache extends BaseCache implements CacheItemPoolInterface {
use CacheItemPoolTrait {
getItem as traitGetItem; // Avoid conflicts
}
}
Metadata Handling:
array serialized to JSON). Validate serialization/deserialization:
$item->setMetadata('tags', ['user', 'admin']);
$tags = json_decode($item->getMetadata()['tags'], true);
TTL Granularity:
$cache->set('key', 'value', 60); // 60 seconds
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...
}
Validate PSR-6 Compliance: Use PHP-CS-Fixer with PSR-6 rules or a custom script to verify implementations.
In-Memory Cache Limits:
SimpleCache does not persist between requests. Use for short-lived tests only.
Custom Cache Items:
Extend CacheItem to add domain-specific metadata:
class UserCacheItem extends CacheItem {
public function setUserId($id) {
$this->metadata['user_id'] = $id;
}
}
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;
}
}
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
});
No Built-in Config: The package is zero-config. All behavior is code-driven.
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
});
PHP Version: Requires PHP 7.4+. Test on Laravel 8+ for compatibility.
How can I help you explore Laravel packages today?