/
AbstractObject.php
101 lines (88 loc) · 2.5 KB
/
AbstractObject.php
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace Sowe\Framework;
use Sowe\Framework\AbstractEntity;
abstract class AbstractObject extends AbstractEntity
{
protected $database;
protected $identifier;
protected $data;
protected $toSave;
public function new()
{
$this->identifier = null;
$this->data = [];
$this->toSave = [];
return $this;
}
public function lazyload($id){
$this->identifier = $id;
$this->data = [];
$this->toSave = [];
return $this;
}
public function load($id)
{
$this->data = $this->get($id);
$this->toSave = [];
if (is_null($this->data)) {
throw new \Exception("No object found");
}
$this->identifier = $id;
unset($this->data[static::$key]);
return $this;
}
public function save()
{
if (empty($this->data)) {
throw new \Exception("There is no data to save");
}
if (is_null($this->identifier)) {
$this->identifier = $this->create($this->data);
if(!$this->identifier){
throw new \Exception("Unable to insert object");
}
} else if(!empty($this->toSave)){
$this->update($this->identifier, $this->toSave);
}
return $this;
}
public function remove()
{
if (is_null($this->identifier)) {
throw new \Exception("Triying to delete non-created object");
}
$this->delete($this->identifier);
}
public function getData($field)
{
if ($field === static::$key) {
if (!is_null($this->identifier)) {
throw new \Exception("Triying to get uninitialized identifier '". $field ."'");
} else {
return $this->identifier;
}
}
if (!isset($this->data[$field])) {
throw new \Exception("Triying to get uninitialized field '". $field ."'");
}
return $this->data[$field];
}
public function setData($field, $value)
{
if(!isset($this->data[$field]) || $this->data[$field] != $value){
$this->data[$field] = $value;
$this->toSave[$field] = $value;
}
return $this;
}
public function getId(){
if(isset($this->data[static::$key])){
return $this->data[static::$key];
}
return $this->identifier;
}
public function setId($id){
$this->setData(static::$key, $id);
return $this;
}
}