cachePrefix . $configKey; $cachedValue = Cache::get($cacheKey); if ($cachedValue !== null) { return $cachedValue; } // 从数据库获取 $config = FarmConfig::where('config_key', $configKey) ->where('is_active', true) ->first(); if (!$config) { // 配置不存在,返回默认值 Cache::put($cacheKey, $defaultValue, $this->cacheTime); return $defaultValue; } $value = $config->getTypedValue(); // 缓存配置值 Cache::put($cacheKey, $value, $this->cacheTime); return $value; } catch (\Exception $e) { Log::error('获取农场配置失败', [ 'config_key' => $configKey, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return $defaultValue; } } /** * 设置配置值 * * @param string $configKey 配置键 * @param mixed $value 配置值 * @return bool */ public function setConfigValue(string $configKey, $value): bool { try { $config = FarmConfig::where('config_key', $configKey)->first(); if (!$config) { Log::warning('尝试设置不存在的农场配置', [ 'config_key' => $configKey, 'value' => $value ]); return false; } $config->setTypedValue($value); $config->save(); // 清除缓存 $cacheKey = $this->cachePrefix . $configKey; Cache::forget($cacheKey); Log::info('农场配置更新成功', [ 'config_key' => $configKey, 'old_value' => $config->getOriginal('config_value'), 'new_value' => $config->config_value ]); return true; } catch (\Exception $e) { Log::error('设置农场配置失败', [ 'config_key' => $configKey, 'value' => $value, 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return false; } } /** * 获取所有配置 * * @return array */ public function getAllConfigs(): array { try { $configs = FarmConfig::where('is_active', true) ->orderBy('config_key') ->get(); $result = []; foreach ($configs as $config) { $result[$config->config_key] = $config->getTypedValue(); } return $result; } catch (\Exception $e) { Log::error('获取所有农场配置失败', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); return []; } } /** * 清除所有配置缓存 * * @return void */ public function clearCache(): void { try { $configs = FarmConfig::pluck('config_key'); foreach ($configs as $configKey) { $cacheKey = $this->cachePrefix . $configKey; Cache::forget($cacheKey); } Log::info('农场配置缓存清除成功'); } catch (\Exception $e) { Log::error('清除农场配置缓存失败', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); } } /** * 获取农场初始化奖励组ID * * @return int */ public function getInitRewardGroupId(): int { return (int) $this->getConfigValue('farm_init_reward_group_id', 0); } /** * 设置农场初始化奖励组ID * * @param int $groupId 奖励组ID * @return bool */ public function setInitRewardGroupId(int $groupId): bool { return $this->setConfigValue('farm_init_reward_group_id', $groupId); } }