loadEnv(); $host = $env['DB_HOST'] ?? '127.0.0.1'; $port = $env['DB_PORT'] ?? '3306'; $db = $env['DB_DATABASE'] ?? ''; $user = $env['DB_USERNAME'] ?? 'root'; $pass = $env['DB_PASSWORD'] ?? ''; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;port=$port;dbname=$db;charset=$charset"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $this->connection = new PDO($dsn, $user, $pass, $options); } catch (PDOException $e) { throw new PDOException($e->getMessage(), (int)$e->getCode()); } } public static function getInstance() { if (self::$instance === null) { self::$instance = new self(); } return self::$instance->connection; } private function loadEnv() { $path = __DIR__ . '/../../.env'; if (!file_exists($path)) { return []; } $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $env = []; foreach ($lines as $line) { if (strpos(trim($line), '#') === 0) continue; list($name, $value) = explode('=', $line, 2); $env[trim($name)] = trim($value); } return $env; } }