Version 3.0
New technologies
This commit is contained in:
62
api/common/Alias/Repository.php
Normal file
62
api/common/Alias/Repository.php
Normal file
@ -0,0 +1,62 @@
|
||||
<?php
|
||||
namespace Common\Alias;
|
||||
|
||||
use Common\Concept\Database;
|
||||
use Common\Concept\Model;
|
||||
use Common\Concept\Repository as RepositoryInterface;
|
||||
|
||||
abstract class Repository implements RepositoryInterface
|
||||
{
|
||||
protected string $table;
|
||||
public function setTable(string $table): RepositoryInterface
|
||||
{
|
||||
$this->table = $table;
|
||||
return $this;
|
||||
}
|
||||
public function getTable(): string
|
||||
{
|
||||
return $this->table;
|
||||
}
|
||||
protected array $properties;
|
||||
public function addProperty(string $name): RepositoryInterface
|
||||
{
|
||||
$this->properties []= $name;
|
||||
return $this;
|
||||
}
|
||||
public function setProperties(array $properties): RepositoryInterface
|
||||
{
|
||||
foreach ($properties as $property) {
|
||||
$this->addProperty($property);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
public function getProperties(): array
|
||||
{
|
||||
return $this->properties;
|
||||
}
|
||||
protected Database $database;
|
||||
public function setDatabase(Database $database): RepositoryInterface
|
||||
{
|
||||
$this->database = $database;
|
||||
return $this;
|
||||
}
|
||||
public function getDatabase(): Database
|
||||
{
|
||||
return $this->database;
|
||||
}
|
||||
|
||||
public function fetchAll(): array
|
||||
{
|
||||
$query = "SELECT * FROM {$this->getTable()}";
|
||||
return array_map([$this, 'load'], $this->getDatabase()->query($query));
|
||||
}
|
||||
|
||||
public function save(Model $model): void
|
||||
{
|
||||
$columns = implode(', ', array_map(function($item) {return "'{$item}'";}, $this->getProperties()));
|
||||
$values = implode(', ', array_map(function($item) {return '?';}, $this->getProperties()));
|
||||
$query = "INSERT INTO {$this->getTable()} ({$columns}) VALUES ({$values})";
|
||||
$values = array_map(function($item) use ($model) {$method = str_replace(' ', '', ucwords(str_replace('_', '', $item)));return $model->{"get{$method}"}();}, $this->getProperties());
|
||||
$this->getDatabase()->prepare($query)->insert($values);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user