server/app/Service/ConfigCacheService.php

63 lines
1.7 KiB
PHP

<?php
namespace App\Service;
use Hyperf\Context\ApplicationContext;
use Psr\SimpleCache\CacheInterface;
use App\Model\SystemConfig as scModel;
class ConfigCacheService
{
protected CacheInterface $cache;
protected string $prefix = 'config:';
public function __construct()
{
$this->cache = ApplicationContext::getContainer()->get(CacheInterface::class);
}
public function loadAll(): void
{
// 加载所有配置项
$configs = scModel::pluck("config_value", "config_key")->toArray();
if (!empty($configs)) {
$configs = array_combine(
array_map(fn($k) => $this->prefix . "$k", array_keys($configs)),
$configs
);
$this->cache->setMultiple($configs);
}
}
public function clearAll(): void
{
// 加载所有配置项
$configs = scModel::pluck("config_key")->toArray();
if (!empty($configs)) {
$keys = array_map(fn($k) => $this->prefix . "$k", $configs);
$this->cache->deleteMultiple($keys);
}
}
public function setItem(string $key, string|null $value): bool
{
return $this->cache->set($this->prefix . $key, $value);
}
public function getItem(string $key): mixed
{
return $this->cache->get($this->prefix . $key);
}
public function removeItem(string $key): bool
{
return $this->cache->delete($this->prefix . $key);
}
public function multipleRemoveItem(array $keys): bool
{
if (count($keys) === 0) return true;
$keys = array_map(fn($k) => $this->prefix . "$k", $keys);
return $this->cache->deleteMultiple($keys);
}
}