前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PHP结合redis实现点赞功能

PHP结合redis实现点赞功能

作者头像
OwenZhang
发布2021-12-08 14:28:09
8410
发布2021-12-08 14:28:09
举报
文章被收录于专栏:Owen's World

第一下载redis包

代码语言:javascript
复制
"predis/predis": "^1.1",

<?php
/**
 * 点赞
 */

namespace app\like\service;

use app\common\DataService;
use app\common\Redis;

class LikeService
{
    const LIKE_TYPE_ALL = 4; //全部
    const LIKE_USER_GIVE_SHOW_CHINESENAME = '赞了您这条';
    const LIKE_USER_RECEIVE_SHOW_CHINESENAME = '我点赞了这条';
    const BLOG_CHINESENAME = '资讯';

    /**
     * 点赞资讯
     * @param int $userId 用户ID
     * @param int $blogId 资讯ID
     */
    public function addLikeBlog($userId, $blogId, $sys)
    {
        $blogInfo = $this->_getBlogInfo($blogId, $sys);
        if (!$blogInfo) return false;
        if ($blogInfo['author_id']) {
            //(资讯创建人)我收到点赞全部列表
            $key = $this->_getMyAllReceiveLikeListKey($blogInfo['author_id'], $sys);
            Redis::getInstance()->redisZadd($key, time(), $blogId . ':blog:' . $userId . ':likeuserid');
        }

        //资讯点赞列表
        $key = $this->_getBlogListKey($blogId, $sys);
        Redis::getInstance()->redisZadd($key, time(), $userId);

        //我的点赞资讯列表
        $key = $this->_getMyLikeBlogListKey($userId, $sys);
        Redis::getInstance()->redisZadd($key, time(), $blogId);

        //我发出点赞全部列表
        $key = $this->_getMyAllGiveLikeListKey($userId, $sys);
        Redis::getInstance()->redisZadd($key, time(), $blogId . ":blog");

        return true;
    }

    /**
     * 取消点赞资讯
     * @param int $userId 用户ID
     * @param int $BlogId 资讯ID
     */
    public function unLikeBlog($userId, $blogId, $sys)
    {
        $blogInfo = $this->_getBlogInfo($blogId, $sys);
        if (!$blogInfo) return false;
        if ($blogInfo['author_id']) {
            //(资讯创建人)我收到点赞全部列表
            $key = $this->_getMyAllReceiveLikeListKey($blogInfo['author_id'], $sys);
            Redis::getInstance()->redisZrem($key, $blogId . ':blog:' . $userId . ':likeuserid');
        }

        //资讯点赞列表
        $key = $this->_getBlogListKey($blogId, $sys);
        Redis::getInstance()->redisZrem($key, $userId);

        //我的点赞资讯列表
        $key = $this->_getMyLikeBlogListKey($userId, $sys);
        Redis::getInstance()->redisZrem($key, $blogId);

        //我的点赞全部列表
        $key = $this->_getMyAllGiveLikeListKey($userId, $sys);
        Redis::getInstance()->redisZrem($key, $blogId . ":blog");

        return true;
    }

    /**
     * 判断资讯是否被点赞
     * @param int $userId 登录用户ID
     * @param int $blogId 资讯ID
     */
    public function isLikeBlog($userId, $blogId, $sys)
    {
        $key = $this->_getMyLikeBlogListKey($userId, $sys);
        $score = Redis::getInstance()->redisZscore($key, $blogId);
        if (empty($score)) {
            return false;
        }
        return true;
    }

    /**
     * 获取资讯点赞数量
     */
    public function getBlogLikeCount($blogId, $sys)
    {
        $key = $this->_getBlogListKey($blogId, $sys);
        $count = (int)Redis::getInstance()->redisZcard($key);
        return ['count' => $count];
    }

    /**
     * 获取资讯评论点赞排序,从高到低排序
     * 返回排序好后评论id数组
     */
    public function getBlogCommentLikeSort($blogId, $sys)
    {
        $key = $this->_getCommentTypeListKey($blogId, 'blog', $sys);
        $list = Redis::getInstance()->redisZRevRange($key, 0, -1, ['WITHSCORES']);
        return $list;
    }

    /**
     * 获取我发出的点赞列表
     * @param int $type 1 帖子 2 资讯 3评论 4全部
     */
    public function getMyAllGiveLikeList($userId, $sys, $type, $pageNo = 1, $pageCount = 10)
    {
        switch ($type) {
            case self::LIKE_TYPE_BLOG:
                $key = $this->_getMyLikeBlogListKey($userId, $sys);
                break;
            default:
                $key = $this->_getMyAllGiveLikeListKey($userId, $sys);
                break;
        }
        $list = Redis::getInstance()->redisZRevRange($key, 0, -1);
        $list = isset($list['data']) ? $list['data'] : [];

        //只展示显示每页数量
        $result = array_slice($list, ($pageNo - 1) * $pageCount, $pageCount);
        $data = [];

        if ($type == self::LIKE_TYPE_ALL) {
            //获取全部信息
            foreach ($result as $k => $value) {
                $detail = explode(':', $value);
                //适应前端数据格式
                $score = Redis::getInstance()->redisZscore($key, $value);
                $likeTime = date("Y-m-d H:i:s", $score);
                $likeTime = DataService::getInstance()->_handleCreateTimeTwo($likeTime);
                $data[$k]['likeTime'] = $likeTime;
                $data[$k]['titleId'] = $detail[0];
                $data[$k]['commentId'] = 0;
                $data[$k]['comment'] = '';

                if (isset($detail[1]) && $detail[1] == 'blog') {
                    $blogInfo = $this->_getBlogInfo($detail[0], $sys);
                    $blogAuthorId = isset($blogInfo['author_id']) ? $blogInfo['author_id'] : 0;
                    $authorInfo = $this->_getAuthorInfo($blogAuthorId, $sys);

                    $data[$k]['sourceUserId'] = $blogAuthorId;
                    $data[$k]['sourceUserNickName'] = isset($authorInfo['author_name']) ? $authorInfo['author_name'] : '';
                    $data[$k]['sourceUserHeadimgurl'] = isset($authorInfo['author_headimgurl']) ? $authorInfo['author_headimgurl'] : '';
                    $data[$k]['likeShowName'] = self::LIKE_USER_RECEIVE_SHOW_CHINESENAME . self::BLOG_CHINESENAME;
                    //点赞来源类型id,1帖子2资讯
                    $data[$k]['likeSourceTypeId'] = self::LIKE_TYPE_BLOG;
                    $data[$k]['likeTypeName'] = self::BLOG_CHINESENAME;
                    $data[$k]['title'] = isset($blogInfo['title']) ? $blogInfo['title'] : '';
                    //评论创建者信息设置为空
                    $data[$k]['commentUserId'] = 0;
                    $data[$k]['commentUserNickName'] = '';
                    $data[$k]['commentUserHeadimgurl'] = '';
                }

            }
        }

        $count = count($data);
        $pagerInfo = [
            "total" => $count,
            "page_no" => $pageNo,
            "page_count" => $pageCount,
            "page_total" => ceil($count / $pageCount)
        ];

        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => ["page_info" => $pagerInfo, "list" => $data]];
    }

    /**
     * 获取我收到的点赞列表
     * @param int $type 1 帖子 2 资讯 3评论 4全部
     */
    public function getMyAllReceiveLikeList($userId, $sys, $type, $pageNo = 1, $pageCount = 10)
    {
        switch ($type) {
            case self::LIKE_TYPE_BLOG:
                $key = $this->_getMyLikeBlogListKey($userId, $sys);
                break;
            default:
                $key = $this->_getMyAllReceiveLikeListKey($userId, $sys);
                break;
        }

        $list = Redis::getInstance()->redisZRevRange($key, 0, -1);
        $list = isset($list['data']) ? $list['data'] : [];

        //只展示显示每页数量
        $result = array_slice($list, ($pageNo - 1) * $pageCount, $pageCount);
        $data = [];

        if ($type == self::LIKE_TYPE_ALL) {
            //获取全部信息
            foreach ($result as $k => $value) {
                $detail = explode(':', $value);
                //适应前端数据格式
                $score = Redis::getInstance()->redisZscore($key, $value);
                $likeTime = date("Y-m-d H:i:s", $score);
                $likeTime = DataService::getInstance()->_handleCreateTimeTwo($likeTime);
                $data[$k]['likeTime'] = $likeTime;
                $data[$k]['titleId'] = $detail[0];
                $data[$k]['commentId'] = 0;
                $data[$k]['comment'] = '';

                if (isset($detail[1]) && $detail[1] == 'blog') {
                    $blogInfo = $this->_getBlogInfo($detail[0], $sys);
                    $blogAuthorId = isset($blogInfo['author_id']) ? $blogInfo['author_id'] : 0;
                    $authorInfo = $this->_getAuthorInfo($blogAuthorId, $sys);

                    $data[$k]['sourceUserId'] = $blogAuthorId;
                    $data[$k]['sourceUserNickName'] = isset($authorInfo['author_name']) ? $authorInfo['author_name'] : '';
                    $data[$k]['sourceUserHeadimgurl'] = isset($authorInfo['author_headimgurl']) ? $authorInfo['author_headimgurl'] : '';
                    $data[$k]['likeShowName'] = self::LIKE_USER_GIVE_SHOW_CHINESENAME . self::BLOG_CHINESENAME;
                    //点赞来源类型id,1帖子2资讯
                    $data[$k]['likeSourceTypeId'] = self::LIKE_TYPE_BLOG;
                    $data[$k]['likeTypeName'] = self::BLOG_CHINESENAME;
                    $data[$k]['title'] = isset($blogInfo['title']) ? $blogInfo['title'] : '';
                    //评论创建者信息
                    $data[$k]['commentUserId'] = 0;
                    $data[$k]['commentUserNickName'] = '';
                    $data[$k]['commentUserHeadimgurl'] = '';
                }

                //点赞者信息
                $userInfo = $this->_getUserInfo($detail[2], $sys);
                $data[$k]['userId'] = $detail[2];
                $data[$k]['userNickName'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
                $data[$k]['userHeadimgurl'] = isset($userInfo['headimgurl']) ? $userInfo['headimgurl'] : '';
            }
        }

        $count = count($data);
        $pagerInfo = [
            "total" => $count,
            "page_no" => $pageNo,
            "page_count" => $pageCount,
            "page_total" => ceil($count / $pageCount)
        ];

        return ["code" => _MSG_SYSTEM_SUCCESS, "msg" => "查询成功", "data" => ["page_info" => $pagerInfo, "list" => $data]];
    }

    /**
     * 获取资讯点赞列表的key
     */
    private function _getBlogListKey($blogId, $sys)
    {
        return "Like:{$sys}:blog:{$blogId}";
    }

    /**
     * 获取我的点赞资讯的key
     */
    private function _getMyLikeBlogListKey($userId, $sys)
    {
        return "Like:{$sys}:users:blogs:{$userId}";
    }


    /**
     * 获取我的全部发出点赞列表的key
     * Like:343:users:all:give:1
     * 在343系统下用户id=1全部发出点赞列表(value=2:blog(文章id为2),score=time时间戳)
     */
    private function _getMyAllGiveLikeListKey($userId, $sys)
    {
        return "Like:{$sys}:users:all:give:{$userId}";
    }

    /**
     * 获取我的全部收到点赞列表的key
     * Like:343:users:all:receive:1
     * 在343系统下用户id=1全部收到点赞列表(value=2:blog(文章id为2),score=time时间戳)
     */
    private function _getMyAllReceiveLikeListKey($userId, $sys)
    {
        return "Like:{$sys}:users:all:receive:{$userId}";
    }


    /**
     * 获取资讯信息
     */
    private function _getBlogInfo($blogId, $sys)
    {
        if (empty($blogId)) {
            return [];
        }

        $blogInfo = BlogInstanceModel::getInstance()->getOneById($blogId, $sys);

        return $blogInfo['data'];
    }

}
复制代码
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年10月25日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis®
腾讯云数据库 Redis®(TencentDB for Redis®)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档