-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntity.php
More file actions
66 lines (54 loc) · 1.93 KB
/
Entity.php
File metadata and controls
66 lines (54 loc) · 1.93 KB
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
<?php
require_once "EntityInterface.php";
require_once "Mysql.php";
abstract class Entity implements EntityInterface
{
protected static $tableName = NULL;
public static function find($clauseWhere): array
{
$sqlQuery = "SELECT * FROM " . static::getTableName() . " WHERE " . $clauseWhere;
$result = Mysql::getInstance()->query($sqlQuery)->fetchAll(PDO::FETCH_ASSOC);
return [];
}
/**
* @return null
*/
public static function getTableName()
{
$reflection = new ReflectionClass(get_called_class());
return NULL !== static::$tableName ? static::$tableName : strtolower($reflection->getName());
}
public function save()
{
$reflection = new ReflectionClass($this);
$props = array();
foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
$propertyName = $property->getName();
if ($propertyName !== "id") {
$props[] = '`' . $propertyName . '` = "' . $this->{$propertyName} . '"';
}
}
$sqlQuery = "INSERT INTO " . static::getTableName() . " SET " . implode(' , ', $props);
Mysql::getInstance()->query($sqlQuery);
}
/**
* @param $id
* @throws Exception
*/
public function load($id)
{
$sqlQuery = "SELECT * FROM " . static::getTableName() . " WHERE id = " . $id;
$result = Mysql::getInstance()->query($sqlQuery)->fetchAll(PDO::FETCH_ASSOC);
$loaded = array_shift($result);
if (NULL === $loaded) {
throw new Exception("Load failed");
}
$reflection = new ReflectionClass($this);
foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
$propertyName = $property->getName();
if (isset($loaded[$propertyName])) {
$this->{$propertyName} = $loaded[$propertyName];
}
}
}
}