laminas/laminas-cache
Laminas Cache provides flexible caching for PHP apps with storage adapters (memory, filesystem, Redis, etc.), plugins, and cache patterns. Includes PSR-6/PSR-16 support, configuration options, and utilities for improving performance and reducing expensive operations.
Installation:
composer require laminas/laminas-cache laminas/laminas-cache-storage-adapter-filesystem
(Use other adapters like redis, memcached, or apcu as needed.)
Basic Cache Usage:
use Laminas\Cache\Storage\Adapter\Filesystem;
use Laminas\Cache\Storage\Plugin\Serializer;
// Create a filesystem adapter
$cache = new Filesystem([
'cache_dir' => storage_path('framework/cache'),
]);
// Add serializer plugin for non-string data
$cache->addPlugin(new Serializer());
// Set and get a value
$cache->setItem('key', ['data' => 'value'], 3600); // TTL: 1 hour
$value = $cache->getItem('key');
PSR-16 Compatibility (SimpleCache):
use Laminas\Cache\Psr\SimpleCache\SimpleCacheDecorator;
$psr16Cache = new SimpleCacheDecorator($cache);
$psr16Cache->set('psr_key', 'psr_value', 3600);
$psrValue = $psr16Cache->get('psr_key');
Leverage Laravel's service container to register and resolve cache adapters:
// In a service provider (e.g., AppServiceProvider)
$this->app->singleton('cache.filesystem', function ($app) {
return new Filesystem([
'cache_dir' => storage_path('framework/cache'),
]);
});
// Resolve in a controller
public function __construct(private $cache) {
$this->cache = $this->cache->filesystem;
}
Output Caching (e.g., views):
$cacheKey = 'view_homepage_' . md5($request->getPathInfo());
if ($this->cache->hasItem($cacheKey)) {
return $this->cache->getItem($cacheKey);
}
$content = view('home')->render();
$this->cache->setItem($cacheKey, $content, 3600);
return $content;
Class/Object Caching:
$expensiveObject = $this->cache->getItem('expensive_object');
if (!$expensiveObject) {
$expensiveObject = new ExpensiveClass();
$this->cache->setItem('expensive_object', $expensiveObject, 86400);
}
Use tags to invalidate related cache items:
// Set with tags
$this->cache->setItem('user_123', $userData, 3600, ['users', 'user_123']);
// Clear by tag
$this->cache->clean(['users']);
// Clear specific item
$this->cache->removeItem('user_123');
$value = $this->cache->get('key', function () {
return computeExpensiveValue();
});
Configure multiple adapters (e.g., filesystem + Redis) and switch dynamically:
// In config/cache.php
'default' => [
'driver' => 'filesystem',
'options' => ['cache_dir' => storage_path('framework/cache')],
],
'redis' => [
'driver' => 'redis',
'options' => ['host' => '127.0.0.1', 'port' => 6379],
],
Serializer plugin or implement __serializeMagic()/__unserializeMagic().Laminas\Cache\Exception\ExceptionInterface when serialization fails.DateInterval (e.g., new DateInterval('P1D') for 1 day).| Adapter | Notes |
|---|---|
| Filesystem | Ensure cache_dir is writable. Use absolute paths. |
| Redis | Requires predis/predis or phpredis. Configure connection options. |
| APCu | Shared-memory; not suitable for clustered environments. |
| Memcached | Requires memcached extension. Use consistent hashing for clusters. |
delete() returns false on failure (not null or exception). Audit plugins if using custom adapters.$lock = $this->cache->getLock('my_lock');
if ($lock->tryLock()) {
// Critical section
$lock->unlock();
}
md5($userId . $request->ip())).setMultiple()/getMultiple() over loops.Laminas\Cache\Storage\Event\EventInterface listeners:
$cache->addPlugin(new \Laminas\Cache\Storage\Plugin\Logger([
'logger' => \Log::channel('cache'),
]));
$stats = $this->cache->getMetadata('stats');
Cache::tags() for tag-based invalidation (requires Laravel's built-in cache system, but Laminas can integrate via Cache::store()).cache.hit/cache.miss events in Laravel:
Cache::extend('laminas', function () {
return new SimpleCacheDecorator($laminasCache);
});
| Error | Cause | Solution |
|---|---|---|
Serialization of 'Closure' is not allowed |
Passing closures to cache. | Avoid caching closures; use serialized data. |
Cache directory not writable |
Filesystem permissions. | chmod -R 775 storage/framework/cache. |
Redis connection failed |
Misconfigured Redis. | Verify host, port, and auth. |
APCu not available |
Extension not installed. | pecl install apcu. |
How can I help you explore Laravel packages today?