This commit is contained in:
William 2022-01-20 22:23:21 +01:00
parent 57136ef50d
commit 972574d293
4 changed files with 49 additions and 34 deletions

View File

@ -2,10 +2,20 @@
class App
{
public array $config;
public object $database;
public object $session;
public function __construct()
{
$config = require __DIR__ . '/../config.php';
$this->config = $config;
// Require configuration file
$this->config = require __DIR__ . '/../config.php';
// Connect to database
$this->database = new Database($this->config['database']);
// Instantiate new session
$this->session = new Session;
}
// Grab model

View File

@ -1,31 +0,0 @@
<?php
// Encapsulates a single connection to a database
class DBHandle
{
private string $host = CONFIG['database']['args']['host'];
private string $db = CONFIG['database']['args']['database'];
private string $user = CONFIG['database']['args']['user'];
private string $pass = CONFIG['database']['args']['password'];
private string $charset = CONFIG['database']['args']['charset'];
public object $dbh;
public function __construct()
{
try {
$this->dbh = $this->connectWithMySQL();
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int)$e->getCode());
}
}
private function connectWithMySQL(): object
{
$dsn = "mysql:host=$this->host;dbname=$this->db;charset=$this->charset";
$options = [
PDO::ATTR_PERSISTENT => true,
];
return new PDO($dsn, $this->user, $this->pass, $options);
}
}

36
app/core/Database.php Normal file
View File

@ -0,0 +1,36 @@
<?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);
}
}

View File

@ -3,9 +3,9 @@
// Handles anything to do with sessions
class Session
{
// TODO: ...
public function __construct()
{
// Start new session if there is none
if (session_status() === PHP_SESSION_NONE)
{
session_start();