1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| class DatabaseConfig { public function __construct( public readonly string $host, public readonly int $port, public readonly string $database, public readonly string $username, public readonly string $password, public readonly string $charset = 'utf8mb4', public readonly array $options = [] ) { if (empty($host)) { throw new InvalidArgumentException('Host cannot be empty'); } if ($port < 1 || $port > 65535) { throw new InvalidArgumentException('Invalid port number'); } } public function getDsn(): string { return "mysql:host={$this->host};port={$this->port};dbname={$this->database};charset={$this->charset}"; } public function toArray(): array { return [ 'host' => $this->host, 'port' => $this->port, 'database' => $this->database, 'username' => $this->username, 'charset' => $this->charset, 'options' => $this->options ]; } }
class ConfigFactory { public static function fromEnv(): DatabaseConfig { return new DatabaseConfig( host: $_ENV['DB_HOST'] ?? 'localhost', port: (int)($_ENV['DB_PORT'] ?? 3306), database: $_ENV['DB_DATABASE'] ?? throw new RuntimeException('DB_DATABASE not set'), username: $_ENV['DB_USERNAME'] ?? 'root', password: $_ENV['DB_PASSWORD'] ?? '', charset: $_ENV['DB_CHARSET'] ?? 'utf8mb4' ); } public static function fromArray(array $config): DatabaseConfig { return new DatabaseConfig( host: $config['host'], port: $config['port'], database: $config['database'], username: $config['username'], password: $config['password'], charset: $config['charset'] ?? 'utf8mb4', options: $config['options'] ?? [] ); } }
|