74 lines
No EOL
2 KiB
PHP
Executable file
74 lines
No EOL
2 KiB
PHP
Executable file
<?php
|
|
|
|
|
|
namespace Venom\Core;
|
|
|
|
|
|
use PDO;
|
|
use PDOException;
|
|
use Venom\Models\DatabaseObject;
|
|
|
|
/**
|
|
* Singleton DatabaseHandler... make sure we only have one connection to the database..
|
|
* @package Venom\Database
|
|
*/
|
|
class DatabaseHandler
|
|
{
|
|
// constants
|
|
public const DB_TYPE = 'type';
|
|
public const DB_HOST = 'host';
|
|
public const DB_PORT = 'port';
|
|
public const DB_USER = 'user';
|
|
public const DB_PASSWORD = 'pw';
|
|
public const DB_DB = 'db';
|
|
public const DB_EXTRA = 'extra';
|
|
private static ?self $instance = null;
|
|
private ?PDO $db = null;
|
|
|
|
public static function get(): DatabaseHandler
|
|
{
|
|
if (self::$instance === null) {
|
|
self::$instance = new self();
|
|
}
|
|
return self::$instance;
|
|
}
|
|
|
|
public function init(array $data): void
|
|
{
|
|
//init instance with the current data... only working if the db is not init!
|
|
if ($this->db != null) {
|
|
return;
|
|
}
|
|
$dsn = '%s:host=%s;dbname=%s;port=%s';
|
|
$connectString = sprintf($dsn, $data[self::DB_TYPE], $data[self::DB_HOST], $data[self::DB_DB], $data[self::DB_PORT] . $data[self::DB_EXTRA]);
|
|
try {
|
|
$this->db = new PDO($connectString, $data[self::DB_USER], $data[self::DB_PASSWORD]);
|
|
} catch (PDOException $e) {
|
|
trigger_error($e->getMessage());
|
|
die($e->getCode());
|
|
}
|
|
}
|
|
|
|
public function getOne(string $query, array $args = []): ?DatabaseObject
|
|
{
|
|
$data = $this->getAll($query, $args);
|
|
if (count($data) > 0) {
|
|
return $data[0];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public function getAll(string $query, array $args = []): array
|
|
{
|
|
$stmt = $this->db->prepare($query);
|
|
$stmt->setFetchMode(PDO::FETCH_CLASS, DatabaseObject::class);
|
|
$stmt->execute($args);
|
|
return $stmt->fetchAll();
|
|
}
|
|
|
|
public function execute(string $query, array $args = []): bool
|
|
{
|
|
$stmt = $this->db->prepare($query);
|
|
return $stmt->execute($args);
|
|
}
|
|
} |