View on GitHub

yii2-cookbook-chinese

Yii Application Development Cookbook(Third Edition)中文翻译

Redis数据库驱动

这个扩展允许你在基于Yii2框架的任何项目中使用Redis键值对存储。它包含了CacheSession两个存储句柄,以及这个扩展,它实现了ActiveRecord模式,用于访问Redis数据库记录。

准备

  1. 按照官方指南http://www.yiiframework.com/doc-2.0/guide-start-installation.html的描述,使用Composer包管理器创建一个新的应用。
  2. 安装存储http://redis.io
  3. 使用如下命令安装migration:
composer require yiisoft/yii2-redis

如何做…

首先,在你的配置文件中配置Connection类:

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

直接使用方法

对于Redis命令的低级使用,你可以使用这个连接组件的executeCommand()方法:

Yii::$app->redis->executeCommand('hmset', ['test_collection', 'key1', 'val1', 'key2', 'val2']);

你也可以使用简化的快捷方式,而不是调用executeCommand

Yii::$app->redis->hmset('test_collection', 'key1', 'val1', 'key2', 'val2')

使用ActiveRecord

欲通过ActiveRecord模式访问Redis记录,你的记录类需要从yii\redis\ActiveRecord基类扩展,并实现attributes()方法:

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

任何模型的主键可以通过primaryKey()方法定义,如果没有指定,它的缺省值是id。如果你没有通过primaryKey()手动执行这个主键的话,它需要被放置在属性列表中。

下面是一个使用例子:

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

工作原理…

这个扩展提供了一个Connection组件,用于对Redis存储记录的低级访问。

你也可以使用一个类ActiveRecord的模型,它带有一些方法的集合(where()limit()offset()indexBy())。其它方法不存在,因为Redis不支持SQL查询。

在Redis中没有表,所以你不能定义via relation via a junction table name。你只需要通过hasMany关系定义一个多对多的关系。

关于Yii的ActiveRecord的一般信息,参考第三章,ActiveRecord,模型和数据库

参考