You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

118 rivejä
2.3 KiB

  1. <?php
  2. namespace Kuxin\Db;
  3. use Kuxin\Model;
  4. use ArrayAccess;
  5. class ORM extends Model implements ArrayAccess
  6. {
  7. /**
  8. * @var array
  9. */
  10. protected $attribute = [];
  11. /**
  12. * @var array
  13. */
  14. protected $original = [];
  15. /**
  16. * 获取单挑数据
  17. * @param mixed $id
  18. * @return $this
  19. */
  20. public function one($id = null)
  21. {
  22. $this->attribute = $this->original = $this->find($id);
  23. return $this;
  24. }
  25. /**
  26. * 保存数据
  27. */
  28. public function save()
  29. {
  30. $data = [];
  31. foreach ($this->attribute as $field => $value) {
  32. if ($field <> $this->getPk() && $value != $this->original[$field]) {
  33. $data[$field] = $value;
  34. }
  35. }
  36. if ($data) {
  37. $this->where([$this->getPk() => $this->original[$this->getPk()]])->update($data);
  38. }
  39. }
  40. /**
  41. * 修改器 设置数据对象的值
  42. * @access public
  43. * @param string $name 名称
  44. * @param mixed $value 值
  45. * @return void
  46. */
  47. public function __set($name, $value)
  48. {
  49. if ($name != $this->getPk()) {
  50. $this->attribute[$name] = $value;
  51. }
  52. }
  53. /**
  54. * 获取器 获取数据对象的值
  55. * @access public
  56. * @param string $name 名称
  57. * @return mixed
  58. */
  59. public function __get($name)
  60. {
  61. return $this->attribute[$name];
  62. }
  63. /**
  64. * 检测数据对象的值
  65. * @access public
  66. * @param string $name 名称
  67. * @return boolean
  68. */
  69. public function __isset($name)
  70. {
  71. return isset($this->attribute[$name]);
  72. }
  73. /**
  74. * 销毁数据对象的值
  75. * @access public
  76. * @param string $name 名称
  77. * @return void
  78. */
  79. public function __unset($name)
  80. {
  81. unset($this->attribute[$name]);
  82. }
  83. // ArrayAccess
  84. public function offsetSet($name, $value)
  85. {
  86. $this->__set($name, $value);
  87. }
  88. public function offsetUnset($name)
  89. {
  90. $this->__unset($name);
  91. }
  92. public function offsetExists($name)
  93. {
  94. return $this->__isset($name);
  95. }
  96. public function offsetGet($name)
  97. {
  98. return $this->__get($name);
  99. }
  100. public function __debugInfo()
  101. {
  102. return $this->attribute ?: $this;
  103. }
  104. }