Init
This commit is contained in:
97
src/Model.php
Normal file
97
src/Model.php
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user