This extension allows you to use Redis key-value storage in any project on the Yii2 framework. It contains the Cache
and Session
storage handlers, as well as the extension, which implements the ActiveRecord pattern for access to the Redis database records.
composer require yiisoft/yii2-redis
First of all, configure the Connection
class in your configuration file:
return [ //.... 'components' => [ 'redis' => [ 'class' => 'yii edisConnection', 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, ], ] ];
For low-level working with Redis commands, you can use the executeCommand
method of the connection component:
Yii::$app->redis->executeCommand('hmset', ['test_collection', 'key1', 'val1', 'key2', 'val2']);
You can also use simplified shortcuts instead of executeCommand
calls:
Yii::$app->redi s->hmset('test_collection', 'key1', 'val1', 'key2', 'val2')
For access to Redis records via the ActiveRecord
pattern, your record class needs to extend from the yii
edisActiveRecord
base class and implement the attributes()
method:
class Customer extends yii edisActiveRecord { public function attributes() { return ['id', 'name', 'address', 'registration_date']; } public function getOrders() { return $this->hasMany(Order::className(), ['customer_id' => 'id']); } }
A primary key of any model can be defined via the primaryKey()
method, which defaults to id
if not specified. The primary key needs to be placed in the attribute list if you do not manually specify it in the primaryKey()
method.
The following is a usage example:
$customer = new Customer(); $customer->name = 'test'; $customer->save(); echo $customer->id; // id will automatically be incremented if not set explicitly // find by query $customer = Customer::find()->where(['name' => 'test'])->one();
The extension provides a Connection
component for low-level access to Redis storage records.
You can also use an ActiveRecord-like model with a limited set of methods (where()
, limit()
, offset(),
and indexBy()
). Other methods do not exist because Redis does not support SQL queries.
There are no tables in Redis, so you cannot define via relations via a junction table name. You can only define many-to-many relations via other hasMany
relations.
For general information on how to use Yii's ActiveRecord, please refer to Chapter 3, ActiveRecord, Model, and Database.
3.145.108.9