model.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. 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, get_object_vars($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. public function __construct($params) {
  57. $this->id = isset($params['id']) ? $params['id'] : null;
  58. $this->attributes = $params;
  59. }
  60. public function save() {
  61. global $dbh;
  62. $this->attributes['id'] = $dbh->pk();
  63. $dbh->insert($this->attributes);
  64. }
  65. public function to_hash() {
  66. return $this->attributes;
  67. }
  68. }