47 lines
1.3 KiB
PHP
47 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace Deploymentcenter\Core;
|
|
|
|
use PDO;
|
|
use PDOException;
|
|
|
|
class Db
|
|
{
|
|
private static ?PDO $instance = null;
|
|
|
|
public static function init(array $config): PDO
|
|
{
|
|
if (self::$instance === null) {
|
|
$dbCfg = isset($config['db']) ? $config['db'] : $config;
|
|
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', $dbCfg['host'], $dbCfg['dbname'], $dbCfg['charset'] ?? 'utf8mb4');
|
|
|
|
$options = [
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
PDO::ATTR_EMULATE_PREPARES => false,
|
|
];
|
|
|
|
try {
|
|
self::$instance = new PDO($dsn, $dbCfg['username'], $dbCfg['password'], $options);
|
|
} catch (PDOException $e) {
|
|
throw new \Exception('Database connection failed: ' . $e->getMessage());
|
|
}
|
|
}
|
|
return self::$instance;
|
|
}
|
|
|
|
public static function connect(array $config): PDO
|
|
{
|
|
return self::init($config);
|
|
}
|
|
|
|
public static function getInstance(): PDO
|
|
{
|
|
if (self::$instance === null) {
|
|
$config = require __DIR__ . '/../../config/config.php';
|
|
return self::init($config);
|
|
}
|
|
return self::$instance;
|
|
}
|
|
}
|