Files
AI-Chat/app/Config/Database.php

40 lines
986 B
PHP

<?php
namespace App\Config;
use PDO;
use PDOException;
class Database
{
private static ?PDO $instance = null;
private function __construct()
{
$configPath = dirname(__DIR__, 2) . '/config/db-config.json';
if (!file_exists($configPath)) {
throw new PDOException('数据库配置文件不存在');
}
$config = json_decode(file_get_contents($configPath), true);
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['dbname']};charset=utf8mb4";
self::$instance = new PDO($dsn, $config['user'], $config['password'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4",
]);
}
public static function getInstance(): PDO
{
if (self::$instance === null) {
new self();
}
return self::$instance;
}
}