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/core/Database.php
2022-01-21 21:16:14 +01:00

30 lines
918 B
PHP

<?php
// Encapsulates a single connection to a database
// TODO: refactor and add different driver implementations
class Database
{
public object $conn; // Holds PDO connection object
public function __construct(array $config)
{
if ($config['name'] !== 'mysql') {
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
{
$dsn = "mysql:host={$args['host']};dbname={$args['database']};charset={$args['charset']}";
$options = [
PDO::ATTR_PERSISTENT => true,
];
return new PDO($dsn, $args['user'], $args['password'], $options);
}
}