36 lines
1.0 KiB
PHP
36 lines
1.0 KiB
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
|
||
|
{
|
||
|
$host = $args['host'];
|
||
|
$database = $args['database'];
|
||
|
$charset = $args['charset'];
|
||
|
$user = $args['user'];
|
||
|
$password = $args['password'];
|
||
|
|
||
|
$dsn = "mysql:host=$host;dbname=$database;charset=$charset";
|
||
|
$options = [
|
||
|
PDO::ATTR_PERSISTENT => true,
|
||
|
];
|
||
|
return new PDO($dsn, $user, $password, $options);
|
||
|
}
|
||
|
}
|