BaseModel.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. class BaseModel {
  3. var $fields;
  4. var $dao;
  5. var $fields_changed;
  6. function __construct( $dao ) {
  7. $this->dao = $dao;
  8. $this->fields_changed = array();
  9. $this->fields = array();
  10. // define fields
  11. //$this->fields['ID'] = '';
  12. }
  13. function get( $field ) {
  14. if (array_key_exists($field, $this->fields)) {
  15. return $this->fields[$field];
  16. }
  17. return null;
  18. }
  19. function set( $field, $value ) {
  20. if (array_key_exists($field, $this->fields)) {
  21. if ($this->fields[$field] != $value) {
  22. $this->fields_changed[$field] = true;
  23. }
  24. $this->fields[$field] = $value;
  25. return true;
  26. }
  27. return false;
  28. }
  29. function setDataFromDB( $data, $field_prefix = '' ) {
  30. foreach ($data as $k_field => $v_value) {
  31. if ($field_prefix != '') {
  32. if (substr($k_field, 0, strlen($field_prefix)) != $field_prefix) {
  33. continue;
  34. }
  35. }
  36. $this->fields[$k_field] = $v_value;
  37. }
  38. }
  39. /**
  40. * Get Model as array.
  41. *
  42. * @return array array('key1' => 'value1', 'key2' => 'value2')
  43. */
  44. function to_array() {
  45. $ret = array();
  46. foreach ($this->fields as $k_field => $v_value) {
  47. $ret[$k_field] = $this->get($k_field);
  48. }
  49. return $ret;
  50. }
  51. /**
  52. * Get Model changed fields as array.
  53. *
  54. * @return array array('key1' => 'value1', 'key2' => 'value2')
  55. */
  56. function changes_to_array() {
  57. $ret = array();
  58. foreach ($this->fields_changed as $k_field => $v_value) {
  59. $ret[$k_field] = $this->get($k_field);
  60. }
  61. return $ret;
  62. }
  63. }