model.php
1.73 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
67
68
69
70
71
72
<?php
/**
* @class Model
* Baseclass for Models in this imaginary ORM
*/
class Model {
public $id, $attributes;
static function create($params) {
$obj = new self(get_object_vars($params));
$obj->save();
return $obj;
}
static function find($id) {
global $dbh;
$found = null;
foreach ($dbh->rs() as $rec) {
if ($rec['id'] == $id) {
$found = new self($rec);
break;
}
}
return $found;
}
static function update($id, $params) {
global $dbh;
$rec = self::find($id);
if ($rec == null) {
return $rec;
}
$rs = $dbh->rs();
foreach ($rs as $idx => $row) {
if ($row['id'] == $id) {
$rec->attributes = array_merge($rec->attributes, get_object_vars($params));
$dbh->update($idx, $rec->attributes);
break;
}
}
return $rec;
}
static function destroy($id) {
global $dbh;
$rec = null;
$rs = $dbh->rs();
foreach ($rs as $idx => $row) {
if ($row['id'] == $id) {
$rec = new self($dbh->destroy($idx));
break;
}
}
return $rec;
}
static function all() {
global $dbh;
return $dbh->rs();
}
public function __construct($params) {
$this->id = isset($params['id']) ? $params['id'] : null;
$this->attributes = $params;
}
public function save() {
global $dbh;
$this->attributes['id'] = $dbh->pk();
$dbh->insert($this->attributes);
}
public function to_hash() {
return $this->attributes;
}
}