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

Yii2 Redis Laravel Package

yiisoft/yii2-redis

Yii2 Redis extension providing Redis-backed cache, mutex, and session handlers plus an ActiveRecord layer for storing and querying structured data in Redis. Requires Redis 2.6.12+ and PHP 7.4+ (best on PHP 8).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require yiisoft/yii2-redis:"~2.1.0"
    
  2. Configure Redis connection in config/web.php:

    'components' => [
        'redis' => [
            'class' => 'yii\redis\Connection',
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
        ],
    ],
    
  3. First use case: Caching

    Yii::$app->cache->set('key', 'value', 3600); // Cache for 1 hour
    $value = Yii::$app->cache->get('key');
    

Implementation Patterns

Cache Integration

  • Replace default cache with Redis:
    'components' => [
        'cache' => [
            'class' => 'yii\redis\Cache',
            'redis' => ['hostname' => 'localhost', 'port' => 6379],
        ],
    ],
    
  • Direct Redis commands via $cache->redis:
    Yii::$app->cache->redis->hset('user:1', 'name', 'John Doe');
    

Session Management

  • Enable Redis sessions:
    'components' => [
        'session' => [
            'class' => 'yii\redis\Session',
        ],
    ],
    
  • Customize session TTL (e.g., 1 day):
    'session' => [
        'class' => 'yii\redis\Session',
        'timeout' => 86400, // 1 day in seconds
    ],
    

ActiveRecord for Redis

  • Define a Redis model:
    class User extends \yii\redis\ActiveRecord {
        public function attributes() {
            return ['id', 'username', 'email'];
        }
    }
    
  • CRUD operations:
    $user = new User();
    $user->username = 'john';
    $user->save();
    
    $user = User::find()->where(['username' => 'john'])->one();
    

Mutex for Locks

  • Lock a critical section:
    $mutex = Yii::$app->redis->getMutex();
    $mutex->acquire(10); // Lock for 10 seconds
    // Critical code here
    $mutex->release();
    

Gotchas and Tips

Pitfalls

  1. Connection Failures:

    • Redis may drop connections. Use retry in Predis options:
      'options' => [
          'parameters' => [
              'retry' => new \Predis\Retry\Retry(
                  new \Predis\Retry\Strategy\ExponentialBackoff(1000, 10000),
                  3
              ),
          ],
      ],
      
    • Monitor connection health with Yii::$app->redis->ping().
  2. ActiveRecord Limitations:

    • No SQL-like queries (where(), orderBy()). Use find() with scopes:
      User::find()->active()->all(); // Active scope
      
  3. Session Expiry:

    • Redis sessions auto-expire after timeout. Ensure timeout is set in config.

Debugging Tips

  • Check Redis keys:
    redis-cli KEYS "*"
    
  • Log Redis operations for debugging:
    Yii::$app->redis->debug(true);
    

Extension Points

  1. Custom Predis Connection: Extend PredisConnection for cluster support:

    'redis' => [
        'class' => 'yii\redis\predis\PredisConnection',
        'parameters' => ['tcp://node1:6379', 'tcp://node2:6379'],
    ],
    
  2. Override Cache Behavior: Extend Cache to add custom serialization:

    class CustomRedisCache extends \yii\redis\Cache {
        public function serializeData($data) {
            return json_encode($data);
        }
    }
    
  3. Use Redis Pipelining: Batch commands for performance:

    $redis = Yii::$app->redis;
    $redis->pipeline(function ($pipe) {
        $pipe->set('key1', 'value1');
        $pipe->set('key2', 'value2');
    });
    
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
andydefer/laravel-cluster
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