From ffd809f76dd50d7a6ee631f21715dca40ec40f44 Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Tue, 24 Feb 2026 10:44:05 +0100 Subject: [PATCH] refactor: database class singleton to use existing connection (#32) This is a half-way fix for #31 so it does not close it. But it does solve the issue of `Too many connections` if the `Database` class when the `Database` class is instanced a lot. The issue of credentials still remain. Reviewed-on: https://codeberg.org/vlw/scaffold/pulls/32 --- src/Database/Database.php | 14 ++++++++++++++ src/Database/Model.php | 6 +++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/Database/Database.php b/src/Database/Database.php index 9d8aa24..013e17d 100644 --- a/src/Database/Database.php +++ b/src/Database/Database.php @@ -19,6 +19,8 @@ private const DEFAULT_USERNAME = "www-data"; private const DEFAULT_PASSWORD = ""; + private static ?Database $instance = null; + /** * Create a new Database instance from credentials * @@ -44,6 +46,16 @@ $_ENV["mariadb"]["user"] = $username; $_ENV["mariadb"]["pass"] = $password; $_ENV["mariadb"]["db"] = $database; + + self::$instance = null; + } + + public static function instance(): static { + if (self::$instance) { + return self::$instance; + } + + return new static(); } /** @@ -56,6 +68,8 @@ $_ENV["mariadb"]["pass"], $_ENV["mariadb"]["db"], ); + + self::$instance = $this; } /** diff --git a/src/Database/Model.php b/src/Database/Model.php index f0c1e01..d689caa 100644 --- a/src/Database/Model.php +++ b/src/Database/Model.php @@ -27,7 +27,7 @@ * @param string $table The target database table */ protected static function create(string $table, array $values): bool { - return new Database()->from($table)->insert($values); + return Database::instance()->from($table)->insert($values); } /** @@ -42,7 +42,7 @@ public readonly array $columns, public readonly array $where ) { - $this->db = new Database(); + $this->db = Database::instance(); } /** @@ -75,7 +75,7 @@ * @return bool Entity exists */ public function isset(): bool { - return $this->_isset ??= new Database() + return $this->_isset ??= Database::instance() ->from($this->table) ->where($this->where) ->limit(1)