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).
Install the package:
composer require yiisoft/yii2-redis:"~2.1.0"
Configure Redis connection in config/web.php:
'components' => [
'redis' => [
'class' => 'yii\redis\Connection',
'hostname' => 'localhost',
'port' => 6379,
'database' => 0,
],
],
First use case: Caching
Yii::$app->cache->set('key', 'value', 3600); // Cache for 1 hour
$value = Yii::$app->cache->get('key');
'components' => [
'cache' => [
'class' => 'yii\redis\Cache',
'redis' => ['hostname' => 'localhost', 'port' => 6379],
],
],
$cache->redis:
Yii::$app->cache->redis->hset('user:1', 'name', 'John Doe');
'components' => [
'session' => [
'class' => 'yii\redis\Session',
],
],
'session' => [
'class' => 'yii\redis\Session',
'timeout' => 86400, // 1 day in seconds
],
class User extends \yii\redis\ActiveRecord {
public function attributes() {
return ['id', 'username', 'email'];
}
}
$user = new User();
$user->username = 'john';
$user->save();
$user = User::find()->where(['username' => 'john'])->one();
$mutex = Yii::$app->redis->getMutex();
$mutex->acquire(10); // Lock for 10 seconds
// Critical code here
$mutex->release();
Connection Failures:
retry in Predis options:
'options' => [
'parameters' => [
'retry' => new \Predis\Retry\Retry(
new \Predis\Retry\Strategy\ExponentialBackoff(1000, 10000),
3
),
],
],
Yii::$app->redis->ping().ActiveRecord Limitations:
where(), orderBy()). Use find() with scopes:
User::find()->active()->all(); // Active scope
Session Expiry:
timeout. Ensure timeout is set in config.redis-cli KEYS "*"
Yii::$app->redis->debug(true);
Custom Predis Connection:
Extend PredisConnection for cluster support:
'redis' => [
'class' => 'yii\redis\predis\PredisConnection',
'parameters' => ['tcp://node1:6379', 'tcp://node2:6379'],
],
Override Cache Behavior:
Extend Cache to add custom serialization:
class CustomRedisCache extends \yii\redis\Cache {
public function serializeData($data) {
return json_encode($data);
}
}
Use Redis Pipelining: Batch commands for performance:
$redis = Yii::$app->redis;
$redis->pipeline(function ($pipe) {
$pipe->set('key1', 'value1');
$pipe->set('key2', 'value2');
});
How can I help you explore Laravel packages today?