From 01842f99b65b06d2647470c3b867719e72dabde7 Mon Sep 17 00:00:00 2001 From: Laria Carolin Chabowski Date: Mon, 5 Oct 2020 21:44:27 +0200 Subject: Introduce some new database wrappers This will allow us to avoid using globals and use the autoloader in the future. --- ratatoeskr/sys/Database.php | 105 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 ratatoeskr/sys/Database.php (limited to 'ratatoeskr/sys/Database.php') diff --git a/ratatoeskr/sys/Database.php b/ratatoeskr/sys/Database.php new file mode 100644 index 0000000..7654e46 --- /dev/null +++ b/ratatoeskr/sys/Database.php @@ -0,0 +1,105 @@ +pdo = $pdo; + $this->prefix = $prefix; + } + + /** + * Create a Database object from a config. + * + * @param array $config + * @return self + */ + public static function fromConfig(array $config): self + { + $pdo = new PDO( + "mysql:host=" . $config["mysql"]["server"] . ";dbname=" . $config["mysql"]["db"] . ";charset=utf8", + $config["mysql"]["user"], + $config["mysql"]["passwd"], + [ + PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', + ] + ); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + return new self($pdo, $config["mysql"]["prefix"]); + } + + /** + * Gets the wrapped PDO object. + * + * @return PDO + */ + public function getPdo(): PDO + { + return $this->pdo; + } + + /** + * Get the table prefix. + * + * @return string + */ + public function getPrefix(): string + { + return $this->prefix; + } + + /** + * Substitutes "PREFIX_" in the input string with the prefix from the config. + * + * @param string $query + * @return string + */ + public function subPrefix(string $query): string // \mystuff\TODO: or can we make this private? + { + return str_replace("PREFIX_", $this->prefix, $query); + } + + /** + * Prepares a SQL statement for usage with the database. + * This will also replace "PREFIX_" with the prefix defined in 'config.php'. + * + * @param string $query The query / statement to prepare. + * @return PDOStatement + */ + public function prepStmt(string $query): PDOStatement // \mystuff\TODO: or can we make this private? + { + return $this->pdo->prepare($this->subPrefix($query)); + } + + /** + * Prepares a query with {@see Database::prepStmt()} and executes it with the remaining arguments. + * + * @param string $query + * @param mixed ...$args + * @return PDOStatement + */ + public function query(string $query, ...$args): PDOStatement + { + $stmt = $this->prepStmt($query); + $stmt->execute($args); + + return $stmt; + } +} -- cgit v1.2.3-70-g09d2