This commit is contained in:
Gregory Letellier
2023-10-26 14:34:20 +02:00
commit a2dc633be4
14 changed files with 5206 additions and 0 deletions

97
src/Model.php Normal file
View File

@@ -0,0 +1,97 @@
<?php
namespace Kletellier\PdoWrapper;
class Model
{
protected mixed $values;
protected string $table;
protected string $pk;
private Db $db;
private bool $new;
public function __construct()
{
$this->db = Db::getInstance();
$this->new = true;
$this->values = array();
$this->pk = "id";
$this->table = $this->getDefaultTableName();
}
public function getTable(): string
{
return $this->table;
}
public function setTable(string $table): self
{
$this->table = $table;
return $this;
}
public function getPk(): string
{
return $this->pk;
}
public function setPk(string $pk): self
{
$this->pk = $pk;
return $this;
}
public function fillData(mixed $data): self
{
$this->values = $data;
$this->new = false;
return $this;
}
public function save(): bool
{
$ret = false;
$qb = $this->newQueryBuilder();
if ($this->new) {
$query = $qb->getPreparedQuery($this->values);
$id = $this->db->insertQuery($query);
if ($id !== false) {
$this->values[$this->pk] = $id;
$this->new = false;
$ret = true;
}
} else {
$query = $qb->getPreparedQuery($this->values, false);
$ret = $this->db->updateQuery($query);
}
return $ret;
}
public function newQueryBuilder(): QueryBuilder
{
return new QueryBuilder($this->table, $this->pk);
}
public function __set($name, $value): void
{
$this->values[$name] = $value;
}
public function __get($name): mixed
{
if (isset($this->values[$name])) {
return $this->values[$name];
}
return null;
}
private function getDefaultTableName(): string
{
$className = get_class($this);
$classNameParts = explode('\\', $className);
$classNameWithoutNamespace = end($classNameParts);
$table = strtolower($classNameWithoutNamespace);
return $table;
}
}