Files
cycle_api/app/Cache/Base/BaseCache.php
2024-02-26 00:41:25 +08:00

72 lines
2.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Cache\Base;
use Illuminate\Support\Facades\Cache;
//用户缓存用户基础信息结构自己组装或等于数据表primary_key为主键
abstract class BaseCache
{
const CACHE_TTL = 60 * 60 * 24 * 3; //缓存时间 3天
public string $primary_prefix; //前缀
public string $primary_key; //值
public string $primary_key_column; //值标识
function setPrimaryKey($primary_key): void
{
$this->primary_key = $primary_key;
}
function getPrimaryKey($primary_key = null): ?string
{
if (empty($primary_key) && empty($this->primary_key)) return null;
if (empty($primary_key)) $primary_key = $this->primary_key;
return $this->primary_prefix . $primary_key;
}
function loadToCache(): bool
{
$sCacheKey = $this->getPrimaryKey();
$aData = $this->loadData();
if (empty($aData)) return false;
return Cache::put($sCacheKey, serialize($aData), self::CACHE_TTL);
}
abstract function loadData(): array|null;
function getCacheData($primary_key = null): array|null
{
if ($primary_key === null) $primary_key = $this->primary_key;
if (empty($primary_key)) return [];
$sCacheKey = $this->getPrimaryKey($primary_key);
$sData = Cache::get($sCacheKey);
if (empty($sData)) {
$this->primary_key = $primary_key;
if($this->loadToCache()) $sData = Cache::get($sCacheKey);
}
if (empty($sData)) return null;
return unserialize($sData);
}
//根据primary_key获取缓存数据单个值不指定key就默认获取所有
function getCacheDataByKey($primary_key = null, $key = null): string|array|bool|null
{
if ($primary_key === null) $primary_key = $this->primary_key;
if (empty($primary_key)) return false;
$aData = $this->getCacheData($primary_key);
if(empty($aData)) return null;
if (empty($key)) return $aData;
return $aData[$key] ?? '';
}
function delCacheData($primary_key = null): bool
{
if ($primary_key === null) $primary_key = $this->primary_key;
if (empty($primary_key)) return false;
$sCacheKey = $this->getPrimaryKey($primary_key);
return Cache::forget($sCacheKey);
}
}