37035-vm/includes/Database.php
2025-12-18 10:12:51 +00:00

48 lines
1.3 KiB
PHP

<?php
class Database {
private static $instance = null;
private $conn;
private function __construct() {
// Database configuration is loaded from db/config.php
require_once __DIR__ . '/../db/config.php';
$host = getenv('DB_HOST') ?: '127.0.0.1';
$db = getenv('DB_NAME');
$user = getenv('DB_USER');
$pass = getenv('DB_PASS');
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;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->conn = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
// In a real app, you'd log this error and show a generic message
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->conn;
}
// Prevent cloning and unserialization
private function __clone() { }
public function __wakeup() { }
}