PHP配置中心与动态配置管理配置管理是应用运维的重要环节。配置中心可以让配置动态变更不需要重启应用。今天说说PHP中的配置管理方案。传统的配置文件方式简单直接但修改配置需要重新部署。php// 文件配置class FileConfig{private array $configs [];private string $configDir;private array $loaded [];public function __construct(string $configDir __DIR__ . /config){$this-configDir rtrim($configDir, /);}public function load(): void{$files glob($this-configDir . /*.php);foreach ($files as $file) {$key basename($file, .php);$this-configs[$key] require $file;$this-loaded[] $key;}}public function get(string $key, mixed $default null): mixed{$keys explode(., $key);$value $this-configs;foreach ($keys as $segment) {if (!is_array($value) || !array_key_exists($segment, $value)) {return $default;}$value $value[$segment];}return $value;}public function set(string $key, mixed $value): void{$keys explode(., $key);$config $this-configs;foreach ($keys as $segment) {if (!isset($config[$segment])) {$config[$segment] [];}$config $config[$segment];}$config $value;}public function all(): array{return $this-configs;}public function reload(): void{$this-configs [];$this-load();}}?// config/app.phpreturn [name MyApp,debug false,env production,timezone Asia/Shanghai,];?// config/database.phpreturn [default mysql,connections [mysql [host localhost,port 3306,database test,username root,password ,charset utf8mb4,],redis [host localhost,port 6379,database 0,],],];?$config new FileConfig();$config-load();echo 应用名称: . $config-get(app.name) . \n;echo 数据库主机: . $config-get(database.connections.mysql.host) . \n;?基于Redis的动态配置中心phpclass RedisConfigCenter{private Redis $redis;private string $prefix config:;private array $localCache [];private int $cacheTtl 60;public function __construct(Redis $redis){$this-redis $redis;}public function get(string $key, mixed $default null): mixed{$cacheKey {$this-prefix}{$key};// 从本地缓存获取if (isset($this-localCache[$cacheKey])) {$cached $this-localCache[$cacheKey];if ($cached[expires] time()) {return $cached[value];}}// 从Redis获取$value $this-redis-get($cacheKey);if ($value false) {return $default;}$decoded json_decode($value, true);$this-localCache[$cacheKey] [value $decoded,expires time() $this-cacheTtl,];return $decoded;}public function set(string $key, mixed $value): void{$cacheKey {$this-prefix}{$key};$this-redis-set($cacheKey, json_encode($value));unset($this-localCache[$cacheKey]);// 发布配置变更通知$this-redis-publish(config_changes, json_encode([key $key,time time(),]));}public function delete(string $key): void{$cacheKey {$this-prefix}{$key};$this-redis-del($cacheKey);unset($this-localCache[$cacheKey]);}public function getMultiple(array $keys): array{$results [];foreach ($keys as $key) {$results[$key] $this-get($key);}return $results;}public function setMultiple(array $configs): void{foreach ($configs as $key $value) {$this-set($key, $value);}}public function getAllWithPrefix(string $prefix ): array{$pattern {$this-prefix}{$prefix}*;$keys $this-redis-keys($pattern);$result [];foreach ($keys as $key) {$configKey str_replace($this-prefix, , $key);$result[$configKey] json_decode($this-redis-get($key), true);}return $result;}public function watchChanges(callable $callback): void{$this-redis-subscribe([config_changes], function ($redis, $channel, $message) use ($callback) {$data json_decode($message, true);$callback($data[key], $data[time]);});}}$redis new Redis();$redis-connect(127.0.0.1, 6379);$configCenter new RedisConfigCenter($redis);$configCenter-set(app.debug, true);$configCenter-set(app.name, MyApp);$configCenter-set(database.host, localhost);$configCenter-set(database.port, 3306);$configCenter-set(cache.ttl, 3600);$configCenter-set(features.new_ui, false);echo 调试模式: . ($configCenter-get(app.debug) ? 开启 : 关闭) . \n;echo 数据库主机: . $configCenter-get(database.host) . \n;echo 缓存TTL: . $configCenter-get(cache.ttl) . \n;echo 默认值: . $configCenter-get(nonexistent, default) . \n;?环境配置的自动切换phpclass EnvironmentConfig{private array $configs [];private string $env;public function __construct(){$this-env $this-detectEnvironment();$this-loadConfigs();}private function detectEnvironment(): string{$env getenv(APP_ENV);if ($env) return $env;if (file_exists(.env.local)) return local;if (file_exists(.env.dev])) return development;if (file_exists(.env.staging)) return staging;return production;}private function loadConfigs(): void{$envFile .env.{$this-env};$baseFile .env;$files [$baseFile, $envFile];foreach ($files as $file) {if (file_exists($file)) {$this-parseEnvFile($file);}}}private function parseEnvFile(string $path): void{$lines file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);foreach ($lines as $line) {$line trim($line);if ($line || str_starts_with($line, #)) continue;if (str_contains($line, )) {[$key, $value] explode(, $line, 2);$key trim($key);$value trim($value);// 处理引号if (str_starts_with($value, ) str_ends_with($value, )) {$value substr($value, 1, -1);}// 类型转换$value match (strtolower($value)) {true true,false false,null null,default $value,};$this-configs[$key] $value;putenv({$key} . (is_bool($value) ? ($value ? true : false) : (string)$value));}}}public function get(string $key, mixed $default null): mixed{return $this-configs[$key] ?? getenv($key) ?: $default;}public function getEnvironment(): string{return $this-env;}public function isLocal(): bool{return $this-env local;}public function isProduction(): bool{return $this-env production;}public function isDevelopment(): bool{return $this-env development;}public function all(): array{return $this-configs;}}$config new EnvironmentConfig();echo 当前环境: . $config-getEnvironment() . \n;echo 是否生产环境: . ($config-isProduction() ? 是 : 否) . \n;?配置是应用的基石。好的配置管理方案可以让运维更轻松开发更高效。文件配置简单明了适合中小项目。配置中心灵活强大适合分布式系统。环境配置通过.env文件自动切换是开发环境的标配。