| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace App\Repositories;
- use App\Model\Mongo\UserRelationModel;
- use App\Model\Mongo\VideoLikeModel;
- use Psr\SimpleCache\CacheInterface;
- class RelationRepository
- {
- /**
- * A用户是否关注了B用户(缓存).
- * @param string $sourceUid 来源用户UID
- * @param string $targetUid 关注目标UID
- * @param bool $cache 是否走缓存.
- * @return bool
- */
- public function userIsFocusOtherUser($sourceUid, $targetUid, $cache = true)
- {
- $sourceUid = strval($sourceUid);
- $targetUid = strval($targetUid);
- if (empty($sourceUid)) {
- // 没有登陆的用户,直接返回false
- return false;
- }
- if ($sourceUid === $targetUid) {
- // 自己=自己,就给关注了.
- return true;
- }
- $cacheKey = 'user_favorite:'. (string)$sourceUid . '_' . (string)$targetUid;
- if (!$cache) {
- $isFocus = $this->userIsFocusOtherUserWithoutCache($sourceUid, $targetUid);
- } else {
- $isFocus = make(CacheInterface::class)->rememberForever($cacheKey, function () use ($sourceUid, $targetUid) {
- return $this->userIsFocusOtherUserWithoutCache($sourceUid, $targetUid);
- });
- }
- return $isFocus;
- }
- /**
- * A用户是否关注了B用户(没缓存).
- * @param $sourceUid
- * @param $targetUid
- * @return bool
- */
- public function userIsFocusOtherUserWithoutCache($sourceUid, $targetUid)
- {
- $isFocus = false; // 默认未关注.
- $mongoKeyId = md5('favorite_' . (string)$sourceUid . '_' . (string)$targetUid);
- $favoriteData = [
- '_id' => $mongoKeyId,
- ];
- $count = make(UserRelationModel::class)->db()
- ->countDocuments($favoriteData);
- $isFocus = boolval($count);
- return $isFocus;
- }
- /**
- * 用户是否点赞过某一个视频(缓存).
- * @param $userCode
- * @param $videoId
- * @param bool $cache
- * @return bool
- */
- public function userIsLikeVideo($userCode, $videoId, $cache = true)
- {
- $cacheKey = 'video_like:'. (string)$userCode . '_' . (string)$videoId;
- if (!$cache) {
- $isLike = $this->userIsLikeVideoWithoutCache($userCode, $videoId);
- } else {
- $isLike = make(CacheInterface::class)->rememberForever($cacheKey, function () use ($userCode, $videoId) {
- return $this->userIsLikeVideoWithoutCache($userCode, $videoId);
- });
- }
- return $isLike;
- }
- /**
- * 用户是否点赞过某一个视频(没缓存).
- * @param $userCode
- * @param $videoId
- * @return bool
- */
- public function userIsLikeVideoWithoutCache($userCode, $videoId)
- {
- $isLike = false; // 默认未点赞.
- $mongoKeyId = substr(md5($userCode . '_' . strval($videoId)), 8, 16);
- $data = [
- '_id' => $mongoKeyId,
- ];
- $count = make(VideoLikeModel::class)->db()
- ->countDocuments($data);
- $isLike = boolval($count);
- return $isLike;
- }
- }
|