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.
Installation:
composer require desarrolla2/cache
No service provider registration is required (PSR-16 compliant).
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');
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();
get(), set(), delete(), clear(), getMultiple(), setMultiple()).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);
}
league/redis-cache, predis/predis):
use League\Cache\FileCache;
$cache = new Cache(new FileCache(storage_path('framework/cache')));
$primary = new Cache(new RedisCache());
$fallback = new Cache(new FileCache());
$cache = new FallbackCache([$primary, $fallback]);
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)
}
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']);
Deferred Expiration with Immutable Items:
$item = $cache->getItem('config');
$item->set($config)->expiresAfter(3600); // 3600 seconds (1 hour)
$cache->save($item);
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);
Breaking Changes in v3.0.0:
Cache facade usage is not supported. Use PSR-16 methods directly or manually bind the package to Laravel's container.remember(), forever()). Use PSR-16 methods exclusively.CacheItem objects are immutable. To update, fetch a new item or re-create it.Adapter Limitations:
tags:user:1) or use a wrapper like taggable-cache.php-lock) for distributed locks.Serialization:
$cache->set('key', json_encode($data)); // Ensure data is serializable
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!');
}
Custom CacheItem:
Extend CacheItem for domain-specific logic:
class UserCacheItem extends CacheItem {
public function setUser(User $user) {
$this->set($user->toArray());
}
}
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
}
PSR-16 Middleware: Chain middleware for pre/post-processing:
$cache = new Cache(
new MiddlewareCache(
new RedisCache(),
[new CompressionMiddleware(), new ValidationMiddleware()]
)
);
Environment-Specific Adapters:
$cache = new Cache(
env('CACHE_DRIVER') === 'redis'
? new RedisCache()
: new FileCache()
);
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;
}
How can I help you explore Laravel packages today?