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)
}
}