2020-03-08 04:37:19 +01:00
|
|
|
<?php
|
2022-04-12 21:56:50 +02:00
|
|
|
/**
|
|
|
|
* Database - DuckBrain
|
2021-10-22 05:34:49 +02:00
|
|
|
*
|
2022-07-15 03:41:48 +02:00
|
|
|
* Clase diseñada para crear y devolver una única instancia PDO (database).
|
2021-10-22 05:34:49 +02:00
|
|
|
* Depende de manera forzada de que estén definidas las constantes:
|
2022-07-15 03:41:48 +02:00
|
|
|
* DB_TYPE, DB_NAME, DB_HOST, DB_USER. DB_PASS
|
2021-10-22 05:34:49 +02:00
|
|
|
*
|
2022-04-12 21:56:50 +02:00
|
|
|
* @author KJ
|
|
|
|
* @website https://kj2.me
|
|
|
|
* @licence MIT
|
2021-10-22 05:34:49 +02:00
|
|
|
*/
|
2020-03-17 18:46:16 +01:00
|
|
|
|
2020-03-08 04:37:19 +01:00
|
|
|
namespace Libs;
|
|
|
|
|
2022-07-15 03:41:48 +02:00
|
|
|
use PDO;
|
|
|
|
use PDOException;
|
|
|
|
use Exception;
|
|
|
|
|
|
|
|
class Database extends PDO {
|
|
|
|
static private ?PDO $db = null;
|
2021-10-22 05:34:49 +02:00
|
|
|
|
|
|
|
private function __construct() {}
|
|
|
|
|
2022-03-17 22:22:04 +01:00
|
|
|
/**
|
2022-07-15 03:41:48 +02:00
|
|
|
* Devuelve una instancia homogénea (singlenton) de la base de datos (PDO).
|
2022-03-17 22:22:04 +01:00
|
|
|
*
|
2022-07-15 03:41:48 +02:00
|
|
|
* @return PDO
|
2022-03-17 22:22:04 +01:00
|
|
|
*/
|
2022-07-15 03:41:48 +02:00
|
|
|
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()
|
|
|
|
);
|
2021-10-22 05:34:49 +02:00
|
|
|
}
|
2022-07-15 03:41:48 +02:00
|
|
|
self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
2021-10-22 05:34:49 +02:00
|
|
|
}
|
|
|
|
return self::$db;
|
2020-03-08 04:37:19 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
?>
|