Use PDO singleton

This commit is contained in:
2024-06-07 20:57:12 -04:00
parent bcca9f5ace
commit d9ffc36fe6
10 changed files with 61 additions and 95 deletions

View File

@@ -27,6 +27,9 @@ class Configuration
/** @var Mode|null The mode in which the library is operating (filled after first connection if not configured) */
public static ?Mode $mode = null;
/** @var PDO|null The PDO instance to use for database commands */
private static ?PDO $_pdo = null;
/**
* Retrieve a new connection to the database
*
@@ -35,21 +38,24 @@ class Configuration
*/
public static function dbConn(): PDO
{
if (empty(self::$pdoDSN)) {
throw new DocumentException('Please provide a data source name (DSN) before attempting data access');
}
$db = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username,
$_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options);
if (is_null(self::$_pdo)) {
if (empty(self::$pdoDSN)) {
throw new DocumentException('Please provide a data source name (DSN) before attempting data access');
}
self::$_pdo = new PDO(self::$pdoDSN, $_ENV['PDO_DOC_USERNAME'] ?? self::$username,
$_ENV['PDO_DOC_PASSWORD'] ?? self::$password, self::$options);
if (is_null(self::$mode)) {
$driver = $db->getAttribute(PDO::ATTR_DRIVER_NAME);
self::$mode = match ($driver) {
'pgsql' => Mode::PgSQL,
'sqlite' => Mode::SQLite,
default => throw new DocumentException(
"Unsupported driver $driver: this library currently supports PostgreSQL and SQLite")
};
if (is_null(self::$mode)) {
$driver = self::$_pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
self::$mode = match ($driver) {
'pgsql' => Mode::PgSQL,
'sqlite' => Mode::SQLite,
default => throw new DocumentException(
"Unsupported driver $driver: this library currently supports PostgreSQL and SQLite")
};
}
}
return $db;
return self::$_pdo;
}
}