45 lines
1.1 KiB
PHP
45 lines
1.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Core;
|
|
|
|
use PDO;
|
|
use PDOException;
|
|
use RuntimeException;
|
|
|
|
class Database
|
|
{
|
|
private static ?PDO $instance = null;
|
|
|
|
private function __construct() {}
|
|
private function __clone() {}
|
|
|
|
public static function getConnection(): PDO
|
|
{
|
|
if (self::$instance === null) {
|
|
$config = require __DIR__ . '/../config/database.php';
|
|
$dsn = sprintf(
|
|
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
|
|
$config['host'],
|
|
$config['port'],
|
|
$config['database'],
|
|
$config['charset']
|
|
);
|
|
|
|
try {
|
|
self::$instance = new PDO(
|
|
$dsn,
|
|
$config['username'],
|
|
$config['password'],
|
|
$config['options']
|
|
);
|
|
} catch (PDOException $e) {
|
|
throw new RuntimeException('Database Connection Failed: ' . $e->getMessage(), (int)$e->getCode());
|
|
}
|
|
}
|
|
|
|
return self::$instance;
|
|
}
|
|
}
|