Redis DB 可以声明为cache组件或作为数据库连接 or both.
当它被声明为cache成分 (使用yii/redis/缓存 http://www.yiiframework.com/doc-2.0/yii-redis-cache.html)可以在该组件中访问它来存储核心价值 pairs 如图所示 http://www.yiiframework.com/doc-2.0/guide-caching-data.html.
$cache = Yii::$app->cache;
// try retrieving $data from cache
$data = $cache->get($key);
// store $data in cache so that it can be retrieved next time
$cache->set($key, $data);
// one more example:
$access_token = Yii::$app->security->generateRandomString();
$cache->add(
// key
$access_token,
// data (can also be an array)
[
'id' => Yii::$app->user->identity->id
'name' => Yii::$app->user->identity->name
],
// expires
60*60*3
);
其他组件也可能开始使用它来缓存建议,例如session
如果配置为这样做或喜欢yii\web\UrlManager http://www.yiiframework.com/doc-2.0/yii-web-urlmanager.html默认情况下,它将尝试在配置文件下定义的任何有效缓存机制中缓存生成的 URL 规则cache
组件如所解释here http://www.yiiframework.com/doc-2.0/yii-web-urlmanager.html#%24cache-detail。因此,在这种情况下找到一些与您不同的存储数据是正常的。
当 Redis 被声明为数据库连接就像您提供的链接中一样,这意味着使用yii\redis\连接 http://www.yiiframework.com/doc-2.0/yii-redis-connection.html类,你可以让你的模型扩展它的\yii\redis\ActiveRecord http://www.yiiframework.com/doc-2.0/yii-redis-activerecord.html类与 Yii 中的任何其他 ActiveRecord 模型一样。到目前为止我知道的唯一区别是您需要手动定义属性,因为没有可解析 NoSQL 数据库的数据库模式。然后只需像任何其他 ActiveRecord 模型一样定义您的规则、场景、关系、事件……:
class Customer extends \yii\redis\ActiveRecord
{
public function attributes()
{
return ['id', 'name', 'address', 'registration_date'];
}
public function rules()
{
return [
['name', 'required'],
['name', 'string', 'min' => 3, 'max' => 12, 'on' => 'register'],
...
];
}
public function attributeLabels() {...}
...
}
所有可用的方法包括save()
, validate()
, getErrors()
, ... 可以找到here http://www.yiiframework.com/doc-2.0/yii-redis-activerecord.html并且应该像任何其他 ActiveRecord 类一样使用如官方指南所示 http://www.yiiframework.com/doc-2.0/guide-db-active-record.html.