67 lines
1.5 KiB
PHP
67 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace Khofmann\Database;
|
|
|
|
use PDO;
|
|
use Khofmann\Config\Config;
|
|
use Exception;
|
|
|
|
/**
|
|
* Facade for database access
|
|
*/
|
|
class Database extends PDO
|
|
{
|
|
// Instances array to ensure singleton pattern
|
|
private static array $instances = [];
|
|
|
|
/**
|
|
* Private since singleton pattern.
|
|
*/
|
|
private function __construct(string $dsn, string $username = null, string $password = null, array $options = null)
|
|
{
|
|
parent::__construct($dsn, $username, $password, $options);
|
|
}
|
|
|
|
/**
|
|
* Disallow clone
|
|
*/
|
|
private function __clone()
|
|
{
|
|
throw new Exception("Cannot clone a singleton.");
|
|
}
|
|
|
|
/**
|
|
* Disallow wakeup
|
|
*/
|
|
private function __wakeup()
|
|
{
|
|
throw new Exception("Cannot unserialize a singleton.");
|
|
}
|
|
|
|
/**
|
|
* Get the instance. Ensures singleton pattern.
|
|
*
|
|
* Loads configuration from `Config` facade
|
|
*/
|
|
public static function getInstance(): Database
|
|
{
|
|
$cls = static::class;
|
|
if (!isset(self::$instances[$cls])) {
|
|
$dataAccess = Config::getDatabase();
|
|
self::$instances[$cls] = new static(
|
|
"mysql:host={$dataAccess["host"]};dbname={$dataAccess["database"]};charset={$dataAccess["charset"]}",
|
|
$dataAccess["user"],
|
|
$dataAccess["passwd"],
|
|
[
|
|
PDO::ATTR_PERSISTENT => false,
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
PDO::ATTR_EMULATE_PREPARES => false,
|
|
]
|
|
);
|
|
}
|
|
|
|
return self::$instances[$cls];
|
|
}
|
|
}
|