cache/redis-adapter
PSR-6 cache pool backed by Redis using the PhpRedis extension. Part of the PHP Cache ecosystem, with shared docs for advanced features like tagging and hierarchy. Supports Redis, RedisArray, and RedisCluster clients.
composer require cache/redis-adapter
\Redis, \RedisArray, or \RedisCluster) and pass it to RedisCachePool:
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$cachePool = new \Cache\RedisCachePool($redis);
config/cache.php):
'stores' => [
'redis' => [
'driver' => 'redis',
'connection' => 'cache', // Laravel's Redis connection
'prefix' => 'laravel_redis_',
],
],
Then use it via the Cache facade:
Cache::put('key', 'value', now()->addMinutes(10));
Caching API Responses:
// Cache a user profile for 5 minutes with a tag for invalidation
$userId = 123;
$cacheKey = "user_profile_{$userId}";
Cache::tags(['user:profile'])->put($cacheKey, $userProfile, now()->addMinutes(5));
// Retrieve the cached profile
$userProfile = Cache::tags(['user:profile'])->get($cacheKey);
// Invalidate on update
Cache::tags(['user:profile'])->clear();
Tag-Based Invalidation: Use tags to group related cache items for bulk invalidation:
// Cache multiple items with the same tag
Cache::tags(['product:pricing'])->put('product_1_price', $price);
Cache::tags(['product:pricing'])->put('product_2_price', $price);
// Invalidate all tagged items
Cache::tags(['product:pricing'])->clear();
Fallback Drivers: Configure a fallback driver in Laravel’s cache config for graceful degradation:
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'fallback' => 'file', // Fallback to file cache if Redis fails
],
Cluster and Replication:
Use \RedisArray or \RedisCluster for high availability:
$redisCluster = new \RedisCluster(null, ['redis1:7000', 'redis2:7001']);
$cachePool = new \Cache\RedisCachePool($redisCluster);
TTL Management: Leverage Redis’s native TTL for automatic expiration:
Cache::put('temp_data', $data, now()->addMinutes(1)); // Expires in 1 minute
Laravel Cache Integration:
Cache::remember() for lazy loading:
$data = Cache::tags(['analytics'])->remember('daily_stats', now()->addDay(), function () {
return Analytics::computeDailyStats();
});
Queue Job Results: Cache job results to avoid recomputation:
Cache::tags(['job:results'])->put("job_{$jobId}", $result, now()->addHours(1));
Full-Page Caching: Cache Blade templates or API responses:
Cache::tags(['page:home'])->put('homepage_html', $html, now()->addMinutes(30));
Laravel Events: Trigger cache invalidation via Laravel events:
// In a UserUpdated listener
Cache::tags(['user:profile'])->clear();
Middleware: Use middleware to cache API responses:
public function handle(Request $request, Closure $next) {
$response = Cache::tags(['api:products'])->remember(
"products_list_{$request->user()->id}",
now()->addMinutes(5),
fn() => $next($request)
);
return $response;
}
Artisan Commands: Clear caches programmatically:
Cache::tags(['config'])->clear();
Testing:
Use Cache::shouldReceive('get')->andReturn(...) in PHPUnit tests to mock Redis responses.
PhpRedis Extension:
phpredis extension causes runtime errors.phpredis is installed and enabled (extension=redis.so in php.ini).php -m | grep redis.Connection Timeouts:
'connections' => [
'cache' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', 6379),
'timeout' => 2.5, // Increase timeout in seconds
],
],
Tagging Overhead:
Memory Management:
maxmemory-policy in Redis config (e.g., allkeys-lru) and use TTLs.Cluster Limitations:
\RedisCluster may not support all Redis commands (e.g., EVAL).\RedisArray for clusters if advanced commands are needed.Laravel Cache Facade Quirks:
forever()) may not behave as expected with Redis.put(), get(), delete()) for consistency.Redis CLI Inspection: Use Redis CLI to debug keys:
redis-cli KEYS "*" # List all keys (use cautiously in production)
redis-cli OBJECT REFCOUNT <key>
PhpRedis Logging:
Enable phpredis logging in php.ini:
redis.logfile = /var/log/phpredis.log
redis.loglevel = 7
Laravel Debugging:
'log' => env('CACHE_LOG', false),
Cache::store('redis')->getStats() to inspect cache hits/misses.Common Errors:
user:123).Prefix Collisions:
laravel_redis_) may collide with other services.'prefix' => 'app_redis_',
Serialization:
Cache::put($key, $value, $ttl, ['serializer' => null]) for custom serialization.Case Sensitivity:
snake_case).Custom Item Class:
Extend \Cache\RedisCacheItem to add metadata or validation:
class CustomCacheItem extends \Cache\RedisCacheItem {
public function setMetadata($metadata) {
$this->metadata = $metadata;
}
}
Event Listeners:
Listen to cache events (e.g., CacheItemPool::clear):
$cachePool->addListener(new class implements \Cache\TagAwareCachePoolListener {
public function onClear(\Cache\TagAwareCachePoolInterface $pool, array $tags) {
// Log or trigger side effects
}
});
Tag Strategies:
Implement custom tagging logic by extending RedisCachePool:
class CustomRedisCachePool extends \Cache\RedisCachePool {
protected function getTagKey($tag) {
return "custom_prefix:{$tag}";
}
}
Fallback Logic:
Override getItem() to implement custom fallback behavior:
$cachePool = new class($redis) extends \Cache\RedisCachePool
How can I help you explore Laravel packages today?