vlw.se/src/Database/Models/Model.php

62 lines
No EOL
1.3 KiB
PHP

<?php
namespace VLW\Database\Models;
use \VV;
use VLW\Database\Database;
require_once VV::root("src/Database/Database.php");
abstract class Model {
const DATE_FORMAT = Database::DATE_FORMAT;
abstract public string $id { get; }
private static Database $_db;
protected readonly Database $db;
private bool $_resolved = false;
private array $_row;
public function __construct(
private readonly string $table,
private readonly array $columns,
private readonly array $where
) {
// Establish once and reuse Database connection
$this->db = self::$_db ??= new Database();
}
private ?array $row {
get {
// Return existing row data
if ($this->_resolved) { return $this->_row; }
$this->_resolved = true;
return $this->_row = $this->db
->from($this->table)
->where($this->where)
->limit(1)
->select($this->columns)
->fetch_assoc() ?? [];
}
}
protected static function create(string $table, array $values): bool {
return new Database()->from($table)->insert($values);
}
public function get(string $key): mixed {
return $this->row[$key] ?? null;
}
public function set(string $key, mixed $value): bool {
$this->_row[$key] = $value;
return $this->db
->from($this->table)
->where($this->where)
->update([$key => $value]);
}
}