Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / examples / restful / remote / lib / model.php
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(get_object_vars($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
28         if ($rec == null) {
29             return $rec;
30         }
31         $rs = $dbh->rs();
32
33         foreach ($rs as $idx => $row) {
34             if ($row['id'] == $id) {
35                 $rec->attributes = array_merge($rec->attributes, get_object_vars($params));
36                 $dbh->update($idx, $rec->attributes);
37                 break;
38             }
39         }
40         return $rec;
41     }
42     static function destroy($id) {
43         global $dbh;
44         $rec = null;
45         $rs = $dbh->rs();
46         foreach ($rs as $idx => $row) {
47             if ($row['id'] == $id) {
48                 $rec = new self($dbh->destroy($idx));
49                 break;
50             }
51         }
52         return $rec;
53     }
54     static function all() {
55         global $dbh;
56         return $dbh->rs();
57     }
58
59     public function __construct($params) {
60         $this->id = isset($params['id']) ? $params['id'] : null;
61         $this->attributes = $params;
62     }
63     public function save() {
64         global $dbh;
65         $this->attributes['id'] = $dbh->pk();
66         $dbh->insert($this->attributes);
67     }
68     public function to_hash() {
69         return $this->attributes;
70     }
71 }
72