laminas/laminas-cache
Laminas Cache provides flexible caching for PHP applications, with adapters for common backends, cache storage, patterns, plugins, and PSR-compatible integrations. Includes tools for configuring, managing, and testing cache behavior in Laminas apps.
Install Required Packages:
composer require laminas/laminas-cache laminas/laminas-cache-storage-adapter-filesystem
(Replace filesystem with your preferred adapter like redis, memcached, etc.)
Configure Cache in Laravel:
Add cache configuration to config/app.php under cache:
'cache' => [
'default' => env('CACHE_DRIVER', 'file'),
'stores' => [
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache'),
],
// Add other adapters (e.g., Redis, Memcached)
],
],
First Use Case: Caching Expensive Operations
use Laminas\Cache\Storage\StorageInterface;
use Illuminate\Support\Facades\Cache;
// Get cache instance (Laravel's Cache facade wraps Laminas under the hood)
$cache = Cache::store('file')->getStore();
// Cache a value with TTL (3600 seconds = 1 hour)
$cache->setItem('expensive_operation_result', $expensiveOperation(), 3600);
// Retrieve cached value
$result = $cache->getItem('expensive_operation_result');
Leverage Laravel's built-in cache system (which uses Laminas under the hood):
// In a service class
public function __construct(
protected StorageInterface $cache // Injected via Laravel's container
) {}
public function fetchData()
{
return $this->cache->hasItem('data')
? $this->cache->getItem('data')
: $this->fetchFromDatabase();
}
Wrap Laminas cache for PSR-16 compatibility:
use Laminas\Cache\Psr\SimpleCache\SimpleCacheDecorator;
// Initialize
$laminasCache = Cache::store('redis')->getStore();
$psr16Cache = new SimpleCacheDecorator($laminasCache);
// Use PSR-16 methods
$psr16Cache->set('key', 'value', 3600);
$value = $psr16Cache->get('key');
Output Caching:
$cacheKey = 'view_' . md5($request->url());
$content = $cache->getItem($cacheKey);
if (!$content) {
$content = view('home')->render();
$cache->setItem($cacheKey, $content, 300); // 5 minutes
}
echo $content;
Class/Object Caching:
$cacheKey = 'user_' . $userId;
$user = $cache->getItem($cacheKey);
if (!$user) {
$user = User::find($userId);
$cache->setItem($cacheKey, $user, 3600);
}
Use tags for grouped invalidation (requires adapter support, e.g., Redis):
// Set with tags
$cache->setItem('user_123', $user, 3600, ['users', 'user:123']);
// Invalidate by tag
$cache->removeItemsByTags(['users']);
Extend functionality with plugins (e.g., serialization for non-serializable data):
use Laminas\Cache\Storage\Plugin\Serializer;
// Add to adapter
$cache->addPlugin(new Serializer());
Serialization Issues:
Serializer plugin or implement __serialize()/__unserialize() in your objects.TTL Misconfiguration:
DateInterval for complex durations:
$cache->setItem('key', $value, new DateInterval('P1D')); // 1 day
Race Conditions:
hasItem + setItem) can fail if another process modifies the cache between checks.addItem for "set if not exists"):
$cache->addItem('key', $value, 3600); // Only sets if 'key' doesn't exist
Adapter-Specific Quirks:
cache_dir to a large partition or use tmpfs.Memory adapter) for ultra-fast but volatile data.Laravel-Specific:
Cache facade does not expose the full StorageInterface.Cache::store('driver')->getStore() to access Laminas methods.Enable Cache Logging:
$cache->setOption('logging', true);
$cache->setOption('log_writer', new \Laminas\Log\Writer\Stream(storage_path('logs/cache.log')));
Clear Cache Programmatically:
$cache->clear(); // Clears all items
$cache->removeItem('key'); // Removes specific item
Benchmark Adapters: Use Laminas’ built-in benchmarks:
vendor/bin/phpbench run --report=aggregate
Custom Adapters:
Implement Laminas\Cache\Storage\StorageInterface for new backends (e.g., S3, DynamoDB).
Plugins: Create plugins for:
Laravel Integration:
Extend Laravel’s CacheManager to support Laminas adapters:
// config/cache.php
'stores' => [
'laminas' => [
'driver' => 'laminas',
'adapter' => Laminas\Cache\Storage\Adapter\Redis::class,
'options' => [
'host' => 'redis',
'port' => 6379,
],
],
],
microtime()).How can I help you explore Laravel packages today?