orm.abstract.class.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. require_once('sql.class.php');
  3. abstract class ORM implements ArrayAccess, JsonSerializable {
  4. // Model definition
  5. protected static $primary_key = 'id';
  6. protected static $foreign_key_suffix = '_id';
  7. protected static $has_one = [];
  8. protected static $has_many = [];
  9. protected static $belongs_to = [];
  10. // Data tracking
  11. private $_data = [];
  12. private $_changed = [];
  13. private $_related = [];
  14. private static $aliases = [];
  15. private static $sql;
  16. // Magic functions
  17. public function __construct($idOrData){
  18. if(empty(self::$aliases[$this->name])){
  19. foreach(self::$belongs_to as $alias => $details){
  20. self::$aliases[$this->name]['belongs_to'][$alias] = array_merge(
  21. [
  22. 'model'=>$alias,
  23. 'foreign_key'=>$alias.$this->foreign_key_suffix
  24. ],
  25. $details
  26. );
  27. }
  28. foreach(self::$has_one as $alias => $details){
  29. self::$aliases[$this->name]['has_one'][$alias] = array_merge(
  30. [
  31. 'model'=>$alias,
  32. 'foreign_key'=>$alias.$this->foreign_key_suffix
  33. ],
  34. $details
  35. );
  36. }
  37. foreach(self::$has_many as $alias => $details){
  38. self::$aliases[$this->name]['has_many'][$alias] = array_merge(
  39. [
  40. 'model'=>$alias,
  41. 'foreign_key'=>$alias.$this->foreign_key_suffix,
  42. 'through'=> null
  43. ],
  44. $details
  45. );
  46. }
  47. }
  48. // Clear relationship definitions to save memory
  49. self::$belongs_to = self::$has_one = self::$has_many =null;
  50. if(is_array($idOrData)){
  51. foreach($idOrData as $key => $val){
  52. $this->_data[$key] = $val;
  53. }
  54. }else{
  55. $this->_data[self::$primary_key] = intval($idOrData);
  56. }
  57. }
  58. public function __destruct(){
  59. $this->__sleep();
  60. $this->_changed = [];
  61. $this->_data = [];
  62. $this->_related = [];
  63. }
  64. public function __get(string $name){
  65. switch($name){
  66. case 'name':
  67. $name=get_class($this);
  68. return substr($name, strrpos($name, '\\')+1);
  69. break;
  70. case 'id':
  71. return $this->get(self::$primary_key);
  72. break;
  73. default:
  74. throw new Exception('Unknown property '.$name);
  75. }
  76. }
  77. public function __set(string $name, $val){
  78. switch($name){
  79. case 'id':case 'name':
  80. throw new Exception('Property '.$name.' is read only');
  81. break;
  82. default:
  83. throw new Exception('Unknown property '.$name);
  84. }
  85. }
  86. public function __call(string $name, array $args){
  87. switch($name){
  88. default:
  89. throw new Exception('Method '.$name.' not implemented');
  90. }
  91. }
  92. public static function __callStatic(string $name, array $args){
  93. throw new Exception('Static method '.$name.' not implemented');
  94. }
  95. public function __sleep(){
  96. $this->save();
  97. }
  98. public function __wakeup(){
  99. $this->reload(true);
  100. }
  101. public function __toString(){
  102. return $this->name.'('.$this->id.')';
  103. }
  104. public function __invoke(){
  105. return $this->_data;
  106. }
  107. public function __clone(){
  108. unset($this->$_data[self::$primary_key]);
  109. }
  110. // JsonSerializable
  111. public function jsonSerialize(){
  112. return $this->_data;
  113. }
  114. // ArrayAccess
  115. public function offsetSet($key, $val){
  116. $this->set($key, $val);
  117. }
  118. public function offsetExists($key){
  119. return $this->has($key);
  120. }
  121. public function offsetUnset($key){
  122. return $this->unset($key);
  123. }
  124. public function offsetGet($key){
  125. return $this->get($key);
  126. }
  127. // Main API
  128. public static function bind(SQL $sql){
  129. self::$sql = $sql;
  130. // @todo handle updating live instances
  131. }
  132. public static function query(...$args){
  133. return self::$sql->query(...$args);
  134. }
  135. // Instance Api
  136. public function values($values){
  137. foreach($values as $key => $val){
  138. $this->set($key, $val);
  139. }
  140. return $this;
  141. }
  142. public function load(bool $force = false){
  143. if(!$force && $this->dirty()){
  144. throw new Exception('Cannot load, there are pending changes');
  145. }else{
  146. if(!is_null($this->id)){
  147. $data = self::query(
  148. "select * " .
  149. "from {$this->name} ".
  150. "where ".self::$primary_key." = ?",
  151. 'i',
  152. $this->id
  153. )->assoc_result;
  154. if($data === false){
  155. throw new Exception("{$this->name} with ".self::$primary_key." of {$this->id} does not exist");
  156. }
  157. $this->_data = $data;
  158. }
  159. }
  160. return $this;
  161. }
  162. public function save(){
  163. if($this->dirty()){
  164. $data = [];
  165. $set = "set ";
  166. $types = '';
  167. foreach($this->_changed as $key){
  168. if(isset($this->_data[$key]) || is_null($this->_data[$key])){
  169. $data[$key] = $this->_data[$key];
  170. }else{
  171. $set .= "{$key} = null";
  172. }
  173. }
  174. foreach($data as $key => $val){
  175. if(is_string($val)){
  176. $types .= 's';
  177. }elseif(is_int($val)){
  178. $types .= 'i';
  179. }elseif(is_double($val)){
  180. $types .= 'd';
  181. }else{
  182. throw new Exception('Unknown data type');
  183. }
  184. $set .= "{$key} = ? ";
  185. }
  186. if(!is_null($this->id) && !in_array(self::$primary_key, $this->_changed)){
  187. $data = array_merge(array_values($data), [$this->id]);
  188. self::query(
  189. "update {$this->name} {$set} where ".self::primary_key." = ?",
  190. $types.'i',
  191. $data
  192. )->execute();
  193. }else{
  194. self::query(
  195. "insert {$this->name} {$set}"
  196. )->execute();
  197. $this->_data[self::$primary_key] = self::$sql->insert_id;
  198. }
  199. }
  200. // Always fetch again from the database in case saving
  201. // forces something to change at the database level
  202. return $this->reload(true);
  203. }
  204. public function reload(bool $force = false){
  205. if($force){
  206. $this->_changed = [];
  207. }
  208. return $this->load($force);
  209. }
  210. public function clear(){
  211. return $this->reload(true);
  212. }
  213. public function get($key){
  214. return $this->_data[$key];
  215. }
  216. public function set($key, $val){
  217. if($key === self::$primary_key && !is_null($this->id)){
  218. throw new Exception('You are not allowed to change the primary key');
  219. }
  220. $this->_data[$key] = $val;
  221. $this->_changed = array_merge($this->_changed, [$key]);
  222. return $this;
  223. }
  224. public function unset($key){
  225. unset($this->_data[$key]);
  226. return $this;
  227. }
  228. public function has($key){
  229. return isset($this->_data[$key]);
  230. }
  231. public function dirty(string $key = null){
  232. if(is_null($key)){
  233. return count($this->_changed) > 0;
  234. }else{
  235. return in_array($key, $this->_changed);
  236. }
  237. }
  238. }
  239. ?>