mirror of https://gitee.com/karson/fastadmin.git
76 lines
1.8 KiB
PHP
76 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace app\common\behavior;
|
|
|
|
use think\Cache;
|
|
use think\Config;
|
|
use think\Log;
|
|
|
|
class RedisSiteConfig
|
|
{
|
|
public function appInit()
|
|
{
|
|
if (self::isEnableRedis()) {
|
|
// 从 Redis 缓存加载配置
|
|
Config::set([
|
|
'site' => self::all()
|
|
]);
|
|
}
|
|
}
|
|
|
|
public static function isEnableRedis(): bool
|
|
{
|
|
return strtolower(Config::get('cache.type')) === 'redis';
|
|
}
|
|
|
|
public static function getCacheKey(): string
|
|
{
|
|
// 缓存键名,根据目录结构哈希,确保不同项目配置不冲突
|
|
return 'fastadmin:site_config:' . md5(__DIR__);
|
|
}
|
|
|
|
/**
|
|
* 获取全部 site 配置
|
|
*/
|
|
public static function all(): array
|
|
{
|
|
try {
|
|
return Cache::remember(self::getCacheKey(), self::loadFromDb(), 0);
|
|
} catch (\Throwable $e) {
|
|
// Redis 挂了也不能影响站点
|
|
Log::error('SiteConfig cache error: ' . $e->getMessage());
|
|
return self::loadFromDb();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 强制刷新缓存
|
|
*/
|
|
public static function refresh(): void
|
|
{
|
|
Cache::rm(self::getCacheKey());
|
|
}
|
|
|
|
/**
|
|
* 从数据库加载 site 配置
|
|
*/
|
|
protected static function loadFromDb(): array
|
|
{
|
|
$config = [];
|
|
$configList = \app\common\model\Config::all();
|
|
foreach ($configList as $k => $v) {
|
|
$value = $v->toArray();
|
|
if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
|
|
$value['value'] = explode(',', $value['value']);
|
|
}
|
|
if ($value['type'] == 'array') {
|
|
$value['value'] = (array)json_decode($value['value'], true);
|
|
}
|
|
$config[$value['name']] = $value['value'];
|
|
}
|
|
|
|
return $config;
|
|
}
|
|
|
|
}
|