Files
duckbrain/src/Libs/Database.php

64 lines
1.6 KiB
PHP

<?php
namespace Libs;
use Exception;
use PDO;
use PDOException;
/**
* Database - DuckBrain
*
* Class designed to create and return a single PDO instance (database).
*
* @author KJ
* @website https://kj2.me
* @license MIT
*/
class Database extends PDO
{
private static array $databases = [];
/**
* Private constructor to prevent direct instantiation.
*/
private function __construct()
{
}
/**
* Returns a homogeneous (singleton) instance of the database (PDO).
*
* @return PDO
* @throws Exception If there is an error connecting to the database.
*/
public static function getInstance(
string $type = 'mysql',
string $host = 'localhost',
string $name = '',
string $user = '',
string $pass = '',
): PDO {
$key = $type . '/' . $host . '/' . $name . '/' . $user;
if (empty(static::$databases[$key])) {
if ($type == 'sqlite') {
$dsn = $type . ':' . $name;
} else {
$dsn = $type . ':dbname=' . $name . ';host=' . $host;
}
try {
static::$databases[$key] = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
throw new Exception(
'Error at connect to database: ' . $e->getMessage()
);
}
static::$databases[$key]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
static::$databases[$key]->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
return static::$databases[$key];
}
}