where('setting_key', $key)->first(); if ($row === null) { return $default; } $value = self::normalizeValue($row->value_json); Cache::put($cacheKey, $value, self::cacheTtlSeconds()); return $value; } /** * 批量读取(逐项走 get;已存在的键会受益于缓存)。 * * @param array $keysToDefault key => default * @return array */ public static function many(array $keysToDefault): array { $out = []; foreach ($keysToDefault as $key => $def) { $out[$key] = self::get($key, $def); } return $out; } /** 删单 key 缓存;写入 lottery_settings 后务必调用(或运维 `php artisan cache:clear`) */ public static function forgetKey(string $key): void { Cache::forget(self::cacheKey($key)); } /** * 写入或更新一行配置并刷新该 key 的缓存。(Seeder / 后续管理端共用) */ public static function put( string $key, mixed $value, string $groupName = 'general', ?string $descriptionZh = null, ): void { LotterySetting::query()->updateOrCreate( ['setting_key' => $key], [ 'value_json' => $value, 'group_name' => $groupName, 'description_zh' => $descriptionZh, ], ); self::forgetKey($key); // 写入后立即预热缓存,下一次 get 可走 Cache::has Cache::put(self::cacheKey($key), self::normalizeValue($value), self::cacheTtlSeconds()); } /** * 批量写入(管理端一次保存多块配置,避免 N 次 HTTP + 审计)。 * * @param list $items */ public static function putMany(array $items): void { if ($items === []) { return; } $keys = array_values(array_unique(array_map( static fn (array $item): string => (string) $item['key'], $items, ))); /** @var array $existing */ $existing = LotterySetting::query() ->whereIn('setting_key', $keys) ->get() ->keyBy('setting_key') ->all(); foreach ($items as $item) { $key = (string) $item['key']; $value = $item['value']; $row = $existing[$key] ?? null; self::put( $key, $value, $row ? (string) $row->group_name : (explode('.', $key)[0] ?? 'general'), $row ? $row->description_zh : null, ); } } public static function cacheKey(string $key): string { return 'lottery_settings:'.$key; } private static function normalizeValue(mixed $value): mixed { return $value; } }