1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
<?php
namespace Core\Table;
use Core\Database\Database;
/**
*
*/
class Table
{
protected $table;
protected $db;
public function __construct(Database $db)
{
$this->db = $db;
if (is_null($this->table)) {
$parts = explode('\\', get_class($this));
$class_name = end($parts);
$this->table = strtolower(str_replace('Table', '', $class_name)) . 's';
}
}
public function all()
{
return $this->db->query('SELECT * FROM ' . $this->table);
}
public function find($id)
{
return $this->query("SELECT * FROM {$this->table} WHERE id = ?", [$id], true);
}
public function create($fields)
{
$sql_parts = [];
$attributes = [];
foreach ($fields as $k => $v) {
$sql_parts[] = "$k = ?";
$attributes[] = $v;
}
$sql_part = implode(', ', $sql_parts);
return $this->query("INSERT INTO {$this->table} SET $sql_part", $attributes, true);
}
public function update($id, $fields)
{
$sql_parts = [];
$attributes = [];
foreach ($fields as $k => $v) {
$sql_parts[] = "$k = ?";
$attributes[] = $v;
}
$attributes[] = $id;
$sql_part = implode(', ', $sql_parts);
return $this->query("UPDATE {$this->table} SET $sql_part WHERE id = ?", $attributes, true);
}
public function delete($id)
{
return $this->query("DELETE FROM {$this->table} WHERE id = ?", [$id], true);
}
public function extract($key, $value)
{
$records = $this->all();
$return = [];
foreach ($records as $v) {
$return[$v->$key] = $v->$value;
}
return $return;
}
public function query($statement, $attributes = null, $one = false)
{
if ($attributes) {
return $this->db->prepare($statement, $attributes, str_replace('Table', 'Entity', get_class($this)), $one);
} else {
return $this->db->query($statement, str_replace('Table', 'Entity', get_class($this)), $one);
}
}
} |