* @return string */ private function getClicksField(): string { return $this->clicks_filed ?? 'clicks'; } /** * Notes : 获取缓存前缀 * @Date : 2021/3/16 5:52 下午 * @Author : < Jason.C > * @return string */ private function getClickCachePrefix(): string { return $this->cachePrefix ?? class_basename(__CLASS__); } /** * Notes : 生成一个缓存KEY * @Date : 2021/3/16 5:52 下午 * @Author : < Jason.C > * @param string|null $appends * @return string */ private function getCacheKey(string $appends = null): string { return $this->getClickCachePrefix() . ':' . $this->getKey() . ':' . $appends; } /** * Notes : 增加点击量 * @Date : 2021/3/17 9:20 上午 * @Author : < Jason.C > * @param int $step */ public function incrementClicks(int $step = 1): void { Cache::increment($this->getCacheKey('clicks'), $step); if (rand(1, $this->saveRate) === 1) { $this->update([$this->getClicksField() => $this->clicks]); } } /** * Notes : 获取缓存的浏览次数 * @Date : 2021/3/16 5:52 下午 * @Author : < Jason.C > * @return int */ public function getClicksAttribute(): int { $clicks = Cache::get($this->getCacheKey('clicks')); if (is_null($clicks)) { return Cache::rememberForever($this->getCacheKey('clicks'), function () { return $this->getAttributes()[$this->getClicksField()]; }); } else { return $clicks; } } }