Files
huangjingfen/pro_v3.5.1/app/services/other/CacheServices.php
panchengyong c1e74d8e68 chore(php): 统一 ScottPan 文件头与注释域名替换
- 按 docs/renew-code-comment.md 将 PHP 文件头改为带边框的 Author 注释\n- 注释中的 crmeb.com 替换为 uj345.cn(代码字符串中的外链未改)\n- 新增 docs/renew-code-comment.md 说明

Made-with: Cursor
2026-03-29 11:22:58 +08:00

99 lines
2.5 KiB
PHP

<?php
// +----------------------------------------------------------------------
// | Author: ScottPan Team
// +----------------------------------------------------------------------
namespace app\services\other;
use app\dao\other\CacheDao;
use app\services\BaseServices;
use think\annotation\Inject;
/**
* Class CacheServices
* @package app\services\other
* @mixin CacheDao
*/
class CacheServices extends BaseServices
{
/**
* @var CacheDao
*/
#[Inject]
protected CacheDao $dao;
/**
* 获取数据缓存
* @param string $key
* @param string|callable|int|array $default 默认值不存在则写入
* @param int $expire
* @return mixed|null
*/
public function getDbCache(string $key, $default, int $expire = 0)
{
$this->dao->delectDeOverdueDbCache();
$result = $this->dao->value(['key' => $key], 'result');
if ($result) {
return json_decode($result, true);
} else {
if ($default instanceof \Closure) {
// 获取缓存数据
$value = $default();
if ($value) {
$this->setDbCache($key, $value, $expire);
return $value;
}
} else {
$this->setDbCache($key, $default, $expire);
return $default;
}
return null;
}
}
/**
* 设置数据缓存存在则更新,没有则写入
* @param string $key
* @param $result
* @param $expire
* @return \crmeb\basic\BaseModel|mixed|\think\Model
* @throws \Exception
*/
public function setDbCache(string $key, $result, $expire = 0)
{
$this->dao->delectDeOverdueDbCache();
$addTime = $expire ? time() + $expire : 0;
if ($this->dao->count(['key' => $key])) {
return $this->dao->update($key, [
'result' => json_encode($result),
'expire_time' => $addTime,
'add_time' => time()
], 'key');
} else {
return $this->dao->save([
'key' => $key,
'result' => json_encode($result),
'expire_time' => $addTime,
'add_time' => time()
]);
}
}
/**
* 删除某个缓存
* @param string $key
*/
public function delectDbCache(string $key = '')
{
if ($key)
return $this->dao->delete($key, 'key');
else
return false;
}
}