This commit is contained in:
Michal Sieciechowicz 2021-03-03 13:41:02 +01:00
parent a3d8bb6131
commit 9204f70e50
4 changed files with 52 additions and 5 deletions

View File

@ -16,4 +16,4 @@ class Job extends BaseModel {
public static function GetLast10() {
return self::QueryAll(self::QueryModel()->GetLast10());
}
}
}

View File

@ -3,6 +3,7 @@
namespace Fufle\Database;
use PDO;
use Fufle\Database\QueryData;
class ConnectionManager {
private static $connection;
@ -12,15 +13,19 @@ class ConnectionManager {
}
public static function Query(string $query, array|object $params = [], string $output = 'stdObject') {
$stmt = self::$connection->prepare($query);
$stmt->execute($params);
$data = new QueryData($query, $params);
$data->normalize();
$stmt = self::$connection->prepare($data->query);
$stmt->execute($data->params);
$stmt->setFetchMode(PDO::FETCH_CLASS, $output);
return $stmt->fetch();
}
public static function QueryAll(string $query, array|object $params = [], string $output = 'stdObject') {
$stmt = self::$connection->prepare($query);
$stmt->execute($params);
$data = new QueryData($query, $params);
$data->normalize();
$stmt = self::$connection->prepare($data->query);
$stmt->execute($data->params);
$stmt->setFetchMode(PDO::FETCH_CLASS, $output);
return $stmt->fetchAll();
}

View File

@ -0,0 +1,29 @@
<?php
namespace Fufle\Database;
class QueryData {
public function __construct(
public string $query,
public array|object $params
) {
}
public function normalize() {
$params = (array)$this->params;
$replaces = [];
foreach($params as $name => $param) {
if (is_array($param)) {
$replaces2 = [];
foreach($param as $i => $p) {
$params[$name.$i.'x'] = $p;
$replaces[] = ':'.$name.$i.'x';
}
unset($params[$name]);
$this->query = str_replace(':'.$name, implode(', ', $replaces), $this->query);
}
}
$this->params = $params;
}
}

View File

@ -9,6 +9,19 @@ abstract class Model {
protected static ?string $table = null;
private static ?IQuery $query = null;
protected static array $fields = [];
public function toArray(): array {
$array = [];
$fields = static::$fields;
foreach($fields as $field) {
if ($this->{$field} ?? null !== null) {
$array[$field] = $this->{$field};
}
}
return $array;
}
protected static function QueryModel() {
if (self::$query === null && self::class !== static::class) {
self::$query = static::QueryModel();