Primer commit del sistema separado falta mejorar mucho
This commit is contained in:
76
shared/database/connection.php
Executable file
76
shared/database/connection.php
Executable file
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
/**
|
||||
* Conexión a Base de Datos Compartida
|
||||
* Utilizada por Discord, Telegram y todos los módulos del sistema
|
||||
*/
|
||||
|
||||
class Database {
|
||||
private static $instance = null;
|
||||
private $connection;
|
||||
|
||||
private function __construct() {
|
||||
$this->connect();
|
||||
}
|
||||
|
||||
private function connect() {
|
||||
try {
|
||||
$host = $_ENV['DB_HOST'] ?? getenv('DB_HOST');
|
||||
$port = $_ENV['DB_PORT'] ?? getenv('DB_PORT');
|
||||
$dbname = $_ENV['DB_NAME'] ?? getenv('DB_NAME');
|
||||
$user = $_ENV['DB_USER'] ?? getenv('DB_USER');
|
||||
$pass = $_ENV['DB_PASS'] ?? getenv('DB_PASS');
|
||||
|
||||
$dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4";
|
||||
|
||||
$options = [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
|
||||
];
|
||||
|
||||
$this->connection = new PDO($dsn, $user, $pass, $options);
|
||||
|
||||
} catch (PDOException $e) {
|
||||
$logFile = __DIR__ . '/../../logs/database_errors.log';
|
||||
$logMessage = date('Y-m-d H:i:s') . " - ERROR DE CONEXIÓN: " . $e->getMessage() . "\n";
|
||||
file_put_contents($logFile, $logMessage, FILE_APPEND);
|
||||
|
||||
throw new Exception("Error de conexión a la base de datos. Consulte los logs para más detalles.");
|
||||
}
|
||||
}
|
||||
|
||||
public static function getInstance() {
|
||||
if (self::$instance === null) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function getConnection() {
|
||||
// Verificar si la conexión está activa
|
||||
try {
|
||||
$this->connection->query('SELECT 1');
|
||||
} catch (PDOException $e) {
|
||||
// Reconectar si la conexión se perdió
|
||||
$this->connect();
|
||||
}
|
||||
|
||||
return $this->connection;
|
||||
}
|
||||
|
||||
// Prevenir clonación
|
||||
private function __clone() {}
|
||||
|
||||
// Prevenir deserialización
|
||||
public function __wakeup() {
|
||||
throw new Exception("No se puede deserializar un singleton.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Función helper para obtener la conexión
|
||||
*/
|
||||
function getDB() {
|
||||
return Database::getInstance()->getConnection();
|
||||
}
|
||||
Reference in New Issue
Block a user