Line | |
---|
1 | <?php |
---|
2 | /** |
---|
3 | * @class Model |
---|
4 | * Baseclass for Models in this imaginary ORM |
---|
5 | */ |
---|
6 | class Model { |
---|
7 | public $id, $attributes; |
---|
8 | static function create($params) { |
---|
9 | $obj = new self($params); |
---|
10 | $obj->save(); |
---|
11 | return $obj; |
---|
12 | } |
---|
13 | static function find($id) { |
---|
14 | global $dbh; |
---|
15 | $found = null; |
---|
16 | foreach ($dbh->rs() as $rec) { |
---|
17 | if ($rec['id'] == $id) { |
---|
18 | $found = new self($rec); |
---|
19 | break; |
---|
20 | } |
---|
21 | } |
---|
22 | return $found; |
---|
23 | } |
---|
24 | static function update($id, $params) { |
---|
25 | global $dbh; |
---|
26 | $rec = self::find($id); |
---|
27 | if ($rec == null) { |
---|
28 | return $rec; |
---|
29 | } |
---|
30 | $rs = $dbh->rs(); |
---|
31 | foreach ($rs as $idx => $row) { |
---|
32 | if ($row['id'] == $id) { |
---|
33 | $rec->attributes = array_merge($rec->attributes, $params); |
---|
34 | $dbh->update($idx, $rec->attributes); |
---|
35 | break; |
---|
36 | } |
---|
37 | } |
---|
38 | return $rec; |
---|
39 | } |
---|
40 | static function destroy($id) { |
---|
41 | global $dbh; |
---|
42 | $rec = null; |
---|
43 | $rs = $dbh->rs(); |
---|
44 | foreach ($rs as $idx => $row) { |
---|
45 | if ($row['id'] == $id) { |
---|
46 | $rec = new self($dbh->destroy($idx)); |
---|
47 | break; |
---|
48 | } |
---|
49 | } |
---|
50 | return $rec; |
---|
51 | } |
---|
52 | static function all() { |
---|
53 | global $dbh; |
---|
54 | return $dbh->rs(); |
---|
55 | } |
---|
56 | |
---|
57 | public function __construct($params) { |
---|
58 | $this->id = $params["id"] || null; |
---|
59 | $this->attributes = $params; |
---|
60 | } |
---|
61 | public function save() { |
---|
62 | global $dbh; |
---|
63 | $this->attributes['id'] = $dbh->pk(); |
---|
64 | $dbh->insert($this->attributes); |
---|
65 | } |
---|
66 | public function to_hash() { |
---|
67 | return $this->attributes; |
---|
68 | } |
---|
69 | } |
---|
70 | |
---|
Note: See
TracBrowser
for help on using the repository browser.