Skip to content

Commit

Permalink
add DB settings: charset, PDO options
Browse files Browse the repository at this point in the history
  • Loading branch information
Link1515 committed Mar 28, 2024
1 parent 53a0d0f commit 82951cd
Showing 1 changed file with 36 additions and 7 deletions.
43 changes: 36 additions & 7 deletions src/DB.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@

class DB
{
/**
* @property array $pdoOptions
*/
private static $pdoOptions = [];


/**
* @property array $pdoCharset
*/
private static $pdoCharset = 'utf8mb4';

/**
* @property array $pdoList
*/
Expand All @@ -32,36 +43,54 @@ private function __construct()
*/
public static function connect($id, $driver, $host, $database, $user, $passwd)
{
if (isset (self::$pdoList[$id])) {
if (isset(self::$pdoList[$id])) {
throw new \RuntimeException('The id "' . $id . '" is already in use.');
}

$defaultOptions = [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];

$options = array_merge(self::$pdoOptions, $defaultOptions);

$pdo = new PDO(
$driver . ':host=' . $host . ';dbname=' . $database,
$driver . ':host=' . $host . ';dbname=' . $database . ';charset=' . self::$pdoCharset,
$user,
$passwd,
$defaultOptions
$options
);

self::$pdoList[$id] = $pdo;
self::$currentPdo = $pdo;
}

/**
* @param array $options
*/
public static function setPDOOptions($options)
{
if (is_array($options)) {
self::$pdoOptions = $options;
}
}

/**
* @param string $charset
*/
public static function setPDOCharset($charset)
{
self::$pdoCharset = $charset;
}

/**
* Use a PDO with a specific id
*
* @param string $id
*/
public static function useConnection($id)
{
if (!isset (self::$pdoList[$id])) {
if (!isset(self::$pdoList[$id])) {
throw new \RuntimeException('PDO with ID "' . $id . '" does not exist');
}

Expand All @@ -78,7 +107,7 @@ public static function useConnection($id)
*/
public static function PDO($id = null)
{
if (isset ($id)) {
if (isset($id)) {
self::useConnection($id);
}

Expand Down

0 comments on commit 82951cd

Please sign in to comment.