Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Redis Adapter Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:
    composer require cache/redis-adapter
    
  2. Set Up Redis Connection: Configure a Redis client (\Redis, \RedisArray, or \RedisCluster) and pass it to RedisCachePool:
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    $cachePool = new \Cache\RedisCachePool($redis);
    
  3. Use with Laravel Cache Facade: Add the adapter to Laravel’s cache configuration (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));
    

First Use Case

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();

Implementation Patterns

Usage Patterns

  1. 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();
    
  2. 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
    ],
    
  3. Cluster and Replication: Use \RedisArray or \RedisCluster for high availability:

    $redisCluster = new \RedisCluster(null, ['redis1:7000', 'redis2:7001']);
    $cachePool = new \Cache\RedisCachePool($redisCluster);
    
  4. TTL Management: Leverage Redis’s native TTL for automatic expiration:

    Cache::put('temp_data', $data, now()->addMinutes(1)); // Expires in 1 minute
    

Workflows

  1. Laravel Cache Integration:

    • Replace default cache drivers with Redis for performance-critical paths.
    • Use Cache::remember() for lazy loading:
      $data = Cache::tags(['analytics'])->remember('daily_stats', now()->addDay(), function () {
          return Analytics::computeDailyStats();
      });
      
  2. Queue Job Results: Cache job results to avoid recomputation:

    Cache::tags(['job:results'])->put("job_{$jobId}", $result, now()->addHours(1));
    
  3. Full-Page Caching: Cache Blade templates or API responses:

    Cache::tags(['page:home'])->put('homepage_html', $html, now()->addMinutes(30));
    

Integration Tips

  1. Laravel Events: Trigger cache invalidation via Laravel events:

    // In a UserUpdated listener
    Cache::tags(['user:profile'])->clear();
    
  2. 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;
    }
    
  3. Artisan Commands: Clear caches programmatically:

    Cache::tags(['config'])->clear();
    
  4. Testing: Use Cache::shouldReceive('get')->andReturn(...) in PHPUnit tests to mock Redis responses.


Gotchas and Tips

Pitfalls

  1. PhpRedis Extension:

    • Issue: Missing phpredis extension causes runtime errors.
    • Fix: Ensure phpredis is installed and enabled (extension=redis.so in php.ini).
    • Debug: Check with php -m | grep redis.
  2. Connection Timeouts:

    • Issue: Redis timeouts may silently fail or throw exceptions.
    • Fix: Configure Laravel’s Redis connection with timeouts:
      'connections' => [
          'cache' => [
              'host' => env('REDIS_HOST', '127.0.0.1'),
              'port' => env('REDIS_PORT', 6379),
              'timeout' => 2.5, // Increase timeout in seconds
          ],
      ],
      
  3. Tagging Overhead:

    • Issue: Tagging adds slight overhead due to Redis hash operations.
    • Fix: Avoid excessive tagging; use tags only for bulk invalidation scenarios.
  4. Memory Management:

    • Issue: Unbounded cache growth can exhaust Redis memory.
    • Fix: Set maxmemory-policy in Redis config (e.g., allkeys-lru) and use TTLs.
  5. Cluster Limitations:

    • Issue: \RedisCluster may not support all Redis commands (e.g., EVAL).
    • Fix: Use \RedisArray for clusters if advanced commands are needed.
  6. Laravel Cache Facade Quirks:

    • Issue: Some Laravel cache methods (e.g., forever()) may not behave as expected with Redis.
    • Fix: Prefer PSR-6 methods (put(), get(), delete()) for consistency.

Debugging

  1. Redis CLI Inspection: Use Redis CLI to debug keys:

    redis-cli KEYS "*"  # List all keys (use cautiously in production)
    redis-cli OBJECT REFCOUNT <key>
    
  2. PhpRedis Logging: Enable phpredis logging in php.ini:

    redis.logfile = /var/log/phpredis.log
    redis.loglevel = 7
    
  3. Laravel Debugging:

    • Enable cache logging in Laravel:
      'log' => env('CACHE_LOG', false),
      
    • Use Cache::store('redis')->getStats() to inspect cache hits/misses.
  4. Common Errors:

    • "Connection refused": Check Redis server status and network connectivity.
    • "Invalid argument": Ensure keys are strings (Redis requires string keys).
    • Tagging failures: Verify tags are properly formatted (e.g., user:123).

Config Quirks

  1. Prefix Collisions:

    • Issue: Default prefixes (e.g., laravel_redis_) may collide with other services.
    • Fix: Customize the prefix in Laravel’s cache config:
      'prefix' => 'app_redis_',
      
  2. Serialization:

    • Issue: Laravel serializes cache items by default, which may not work for complex objects.
    • Fix: Use Cache::put($key, $value, $ttl, ['serializer' => null]) for custom serialization.
  3. Case Sensitivity:

    • Issue: Redis keys are case-sensitive. Mixed-case keys may cause inconsistencies.
    • Fix: Standardize key casing (e.g., snake_case).

Extension Points

  1. Custom Item Class: Extend \Cache\RedisCacheItem to add metadata or validation:

    class CustomCacheItem extends \Cache\RedisCacheItem {
        public function setMetadata($metadata) {
            $this->metadata = $metadata;
        }
    }
    
  2. 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
        }
    });
    
  3. Tag Strategies: Implement custom tagging logic by extending RedisCachePool:

    class CustomRedisCachePool extends \Cache\RedisCachePool {
        protected function getTagKey($tag) {
            return "custom_prefix:{$tag}";
        }
    }
    
  4. Fallback Logic: Override getItem() to implement custom fallback behavior:

    $cachePool = new class($redis) extends \Cache\RedisCachePool
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor