Weave 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

Redis cache, session, mutex, and ActiveRecord support for Yii 2. Store and query structured data in Redis using a familiar ActiveRecord API, with cache and session handlers included.

View on GitHub
Deep Wiki
Context7

Getting Started

This is a Yii 2 extension, not a Laravel package — there is no service provider, no config/database.php entry, and no Redis:: facade. Day-to-day, you use it when you are maintaining or integrating with a Yii 2 codebase and want the Redis roles you normally fill with predis, Cache::store('redis'), the redis session driver, and Cache::lock().

Install and pin the branch (PHP 7.4+, PHP 8 recommended, Redis >= 2.6.12):

composer require --prefer-dist yiisoft/yii2-redis:"~2.1.0"

Register the connection component in the app config (the equivalent of Laravel's redis connection block):

'components' => [
    'redis' => [
        'class'    => 'yii\redis\Connection',
        'hostname' => 'localhost',
        'port'     => 6379,
        'database' => 0,
    ],
],

Read docs/guide/README.md first, then the four topic pages — they map almost 1:1 onto the Laravel concerns you already know:

Laravel This package
Redis::connection() yii\redis\Connection (Yii::$app->redis)
Cache::store('redis') yii\redis\Cache
redis session driver yii\redis\Session
Cache::lock() yii\redis\Mutex
Eloquent yii\redis\ActiveRecord

First use case: swap the cache component. It is the lowest-risk, highest-payoff adoption — no schema, no code changes beyond the config key:

'cache' => ['class' => 'yii\redis\Cache'],

Everything that writes through Yii::$app->cache now lands in Redis. Verify with redis-cli MONITOR while you browse a page.

Implementation Patterns

Cache with an escape hatch. The component implements yii\caching\CacheInterface, so get/set/add/delete/flush/mget all work. When you need a raw command, reach through $redis rather than opening a second connection:

Yii::$app->cache->set('user:42', $payload, 3600);

$r = Yii::$app->cache->redis;   // yii\redis\ConnectionInterface
$r->hset('cart:42', 'sku-1', 3);
$r->hget('cart:42', 'sku-1');

Raw commands on the connection. Connection implements __call, so any Redis command is callable method-style: Yii::$app->redis->zadd('board', 100, 'alice'). For dynamic command names use executeCommand('SET', ['k', 'v']). This is your Redis::command() equivalent and is the pattern to use for anything the typed components don't cover.

Standalone-component configuration. Each component can carry its own connection, exactly like Laravel lets you inline a connection on a store. Useful for isolated session or cache DBs:

'session' => [
    'class' => 'yii\redis\Session',
    'redis' => ['hostname' => 'localhost', 'port' => 6379, 'database' => 1],
],

Mutex for critical sections. Configure yii\redis\Mutex as the mutex component and swap Cache::lock(...)->get(...) for $mutex->acquire($name, $timeout) / $mutex->release($name). Wrap in try/finally — there is no ->block() callback sugar.

ActiveRecord. Subclass yii\redis\ActiveRecord, declare attributes(), optionally override primaryKey() (defaults to id). Persistence mirrors Eloquent: new Model(); $m->attributes = [...]; $m->save(); and the id auto-increments via INCR when unset. Relations work as usual with hasMany/hasOne — including across storage engines (Redis model ↔ SQL model) — but via is unsupported since there are no join tables.

class Customer extends \yii\redis\ActiveRecord
{
    public function attributes() { return ['id', 'name', 'address', 'status']; }
    public function getOrders()  { return $this->hasMany(Order::class, ['customer_id' => 'id']); }
}

$c = Customer::find()->where(['name' => 'test'])->one();
$c = Customer::find()->active()->all();   // custom scope on a CustomerQuery subclass

Predis vs phpredis. yii\redis\Connection is the native (phpredis-style) client; yii\redis\predis\PredisConnection is the Predis-backed one with sentinel and cluster support (parameters accepts a single DSN or an array of sentinel nodes). Choose Predis when you need TLS/sentinel/retry policy expressed in config.

Integration tip: keep Redis models out of your request-critical path in read scenarios — fetch by primary key or precomputed key, not by query — and drive writes through the cache/queue layer so the store stays a cache, not a source of truth.

Gotchas and Tips

  • No SQL semantics in ActiveQuery. The guide lists where(), limit(), offset(), orderBy(), and indexBy() as unsupported, and via relations are impossible. Filtering is effectively in-PHP over fetched records — so design keys (customer:{id}, sorted sets, hashes) to make the query unnecessary. Validate against the exact version you install rather than trusting the translated docs.
  • No prefixing like Laravel's redis.options.prefix. Cache/Session use $keyPrefix; raw Yii::$app->redis calls get nothing. If you share a database with another app, prefix manually or use a separate database index.
  • Predis cluster mode is not a drop-in. Per the guide, PredisConnection cluster support does not back the Cache, Session, ActiveRecord, or Mutex component interfaces. Don't assume you can enable cluster and keep the same component config.
  • Sessions require replacing the component, not just pointing it at Redis. Yii::$app->session keeps working, but session.save_handler-style ini config is irrelevant here — Yii handles it in-process.
  • TLS is configured three different ways (useSSL + contextOptions, scheme => 'tls', or Predis DSN). Pick one and confirm the port; a mismatched scheme gives a silent connection timeout rather than a clear error.
  • database selection happens on connect. Reusing a connection across components with different database values will bite you — give each component its own connection when the DB index matters.
  • Debugging: redis-cli MONITOR is your best tool; the connection is lazy, so a config error surfaces at first command, not at bootstrap. For profiling, wrap calls in Yii::beginProfile() rather than expecting query logging.
  • Extension points: subclass yii\redis\Connection to add helpers or override init() for auth/SELECT; subclass yii\redis\ActiveQuery for scopes; subclass Cache to override key generation or serialization. These are the sanctioned seams — avoid monkey-patching command behavior.
  • Mutex is not reentrant. Acquiring the same lock twice in one request will deadlock against yourself. Match the timeout to your worst-case critical section, and always release in finally.
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.
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core