您的位置:首页 > 数据库 > Redis

关于Yii2中redis扩展的使用

2014-12-02 12:03 405 查看
yii2支持了redis扩展,不需要在本地下载php的扩展库就可以很好的使用

1.下载windows的redis安装包打开cmd,进入安装包目录,使用redis-server.exe redis.conf,开启redis服务器,再打开一个cmd窗口,redis-cli.exe -h IP -p 6379

备注:现在Windows下的redis可以到这里下载:https://github.com/dmajkic/redis/downloads

redis windows下的环境搭建

下载地址:https://github.com/dmajkic/redis/downloads 下载下来的包里有两个,

一个是32位的,一个是64位的。根据自己的实情情况选择,我的是32bit,

把这个文件夹复制到其它地方,比如D:\redis 目录下。

打开一个cmd窗口 使用cd命令切换目录到d:\redis 运行 redis-server.exe redis.conf

如果想方便的话,可以把redis的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个redis.conf可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:



下载下来解压即可使用。

2.下载yii2的redis的安装包,下载地址为:https://github.com/yiisoft/yii2-redis

3.把下载的扩展文件放到vendor/yiisoft/下,命名为yii2_redis

4.修改vender/yiisoft/下的extensions.php,加入redis扩展

代码如图:



修改common/config.php文件,设置redis组件,代码如图



接下来我们就可以很轻松的到控制器中写个测试方法来体验一下redis了,测试demo如下:



The following is an example model called
Customer
:

class Customer extends \yii\redis\ActiveRecord
{
/**
* @return array the list of attributes for this record
*/
public function attributes()
{
return ['id', 'name', 'address', 'registration_date'];
}

/**
* @return ActiveQuery defines a relation to the Order record (can be in other database, e.g. elasticsearch or sql)
*/
public function getOrders()
{
return $this->hasMany(Order::className(), ['customer_id' => 'id']);
}

/**
* Defines a scope that modifies the `$query` to return only active(status = 1) customers
*/
public static function active($query)
{
$query->andWhere(['status' => 1]);
}
}

Usage example:

$customer = new Customer();
$customer->attributes = ['name' => 'test'];
$customer->save();
echo $customer->id; // id will automatically be incremented if not set explicitly

$customer = Customer::find()->where(['name' => 'test'])->one(); // find by query
$customer = Customer::find()->active()->all(); // find all by query


@author http://www.yiicms.net
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: