48 lines
1.2 KiB
PHP
48 lines
1.2 KiB
PHP
<?php
|
|
/**
|
|
* Database - DuckBrain
|
|
*
|
|
* Clase diseñada para crear y devolver una única instancia PDO (database).
|
|
* Depende de manera forzada de que estén definidas las constantes:
|
|
* DB_TYPE, DB_NAME, DB_HOST, DB_USER. DB_PASS
|
|
*
|
|
* @author KJ
|
|
* @website https://kj2.me
|
|
* @licence MIT
|
|
*/
|
|
|
|
namespace Libs;
|
|
|
|
use PDO;
|
|
use PDOException;
|
|
use Exception;
|
|
|
|
class Database extends PDO {
|
|
static private ?PDO $db = null;
|
|
|
|
private function __construct() {}
|
|
|
|
/**
|
|
* Devuelve una instancia homogénea (singlenton) de la base de datos (PDO).
|
|
*
|
|
* @return PDO
|
|
*/
|
|
static public function getInstance() : PDO {
|
|
if (is_null(self::$db)) {
|
|
$dsn = DB_TYPE.':dbname='.DB_NAME.';host='.DB_HOST;
|
|
try {
|
|
self::$db = new PDO($dsn, DB_USER, DB_PASS);
|
|
} catch (PDOException $e) {
|
|
echo "<pre>";
|
|
throw new Exception(
|
|
'Error at connect to database: ' . $e->getMessage()
|
|
);
|
|
}
|
|
self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
self::$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
|
|
}
|
|
return self::$db;
|
|
}
|
|
}
|
|
?>
|