This repository has been archived on 2023-01-06. You can view files and clone it, but cannot push or open issues or pull requests.
web/app/lib/App/Core/Database.php

40 lines
1.1 KiB
PHP
Raw Normal View History

2022-01-20 21:23:21 +00:00
<?php
2022-03-02 06:15:12 +00:00
namespace App\Core;
use \Exception;
use \PDO;
use \PDOException;
/**
* Encapsulates a single connection to a database.
* TODO: Refactor and add different driver implementations.
*/
2022-01-20 21:23:21 +00:00
class Database
{
2022-01-23 21:56:36 +00:00
public PDO $conn;
2022-01-20 21:23:21 +00:00
public function __construct(array $config)
{
2022-01-23 21:56:36 +00:00
if ($config['name'] !== 'mysql')
{
2022-01-20 21:23:21 +00:00
throw new Exception("Database error: ".$config['name']." is not implemented");
}
try {
$this->conn = $this->connectWithMySQL($config['args']);
} catch (PDOException $e) {
throw new PDOException("Database error: " . $e->getMessage());
}
}
private function connectWithMySQL(array $args): object
{
2022-01-21 20:16:14 +00:00
$dsn = "mysql:host={$args['host']};dbname={$args['database']};charset={$args['charset']}";
2022-01-20 21:23:21 +00:00
$options = [
PDO::ATTR_PERSISTENT => true,
2022-01-26 15:23:49 +00:00
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION // In PHP 8 and above, this will be the default mode.
2022-01-20 21:23:21 +00:00
];
2022-01-21 20:16:14 +00:00
return new PDO($dsn, $args['user'], $args['password'], $options);
2022-01-20 21:23:21 +00:00
}
}