php操作redis实现朋友圈投票

13 篇文章 1 订阅
9 篇文章 0 订阅

php操作redis实现朋友圈投票


案例需求
1:每人每天可投票一次
2:有固定的被投票人

实现
1.新建一个vote类,有user投票人和vote被投票人两个变量

use think\cache\driver\Redis;

class Vote
{
    public $user;//投票者
    public $vote;//被投票者
    function __construct($user = '', $vote = '')
    {
        $this->user = $user;
        $this->vote = $vote;
        $redis = new Redis();
        $this->redis = $redis;
    }

//投票
public function vote()
{
    $num = $this->redis->get('user'.$this->user);//获取当前投票人是否投过票。
    if($num){
        return '今天投票过了';
    }
    $total = $this->redis->handler()->incr('vote'.$this->vote,1);//被投票人加一票数
    if($total){//投票成功,24小时内该人不可投票
        $this->redis->handler()->setex('user'.$this->user,86400,1);
    }
    return $total;
}

//获取投票记录
public function getList()
{
    $userList = $this->redis->get('userList');//获取所有投票人
    foreach ($userList as &$value){//遍历投票人
            $total = $this->redis->get('vote'.$value['id']);
            $value['num'] = intval($total);//把投票记录根据id给对应的被投票人
    }
    return $userList;
}

//被投票人
public function voteUser()
{
	//创建一个被投票人数组
    $list = array(array('id'=>'1','name'=>'sea'),array('id'=>'2','name'=>'seai'),array('id'=>'3','name'=>'seaiio'),);
    $this->redis->set('userList',json_encode($list));
    $userList = $this->redis->get('userList');
    return $userList;
}
}

测试

1.创建一个vote类

	 $user = new Vote('seaiio',1);用户seaiio给id为1的人投票
	  dump($user->voteUser());//获取被投票人的列表

结果

string(77) "[{"id":"1","name":"sea"},{"id":"2","name":"seai"},{"id":"3","name":"seaiio"}]"

2.投票

 dump($user->vote());///执行两次。

结果

int(2)
string(18) "今天投票过了"

3.查看投票记录

 dump($user->getList());

结果

array(3) {
  [0] => array(3) {
    ["id"] => string(1) "1"
    ["name"] => string(3) "sea"
    ["num"] => int(13)
  }
  [1] => array(3) {
    ["id"] => string(1) "2"
    ["name"] => string(4) "seai"
    ["num"] => int(2)
  }
  [2] => array(3) {
    ["id"] => string(1) "3"
    ["name"] => string(6) "seaiio"
    ["num"] => int(0)
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值