Files
water_new/app/Traits/HasClicks.php
2023-03-08 09:16:04 +08:00

88 lines
2.0 KiB
PHP

<?php
namespace App\Traits;
use Illuminate\Support\Facades\Cache;
/**
* 预期给所有拥有浏览计数的模型使用
* 使用缓存,计算浏览量,定期更新缓存至数据库中
*/
trait HasClicks
{
protected int $saveRate = 20;
/**
* Notes : 获取点击量的字段
*
* @Date : 2021/3/17 9:39 上午
* @Author : <Jason.C>
* @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;
}
}
}