orm.abstract.class.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 __get(string $name){
  59. switch($name){
  60. case 'name':
  61. $name=get_class($this);
  62. return substr($name, strrpos($name, '\\')+1);
  63. break;
  64. case 'id':
  65. return $this->get(self::$primary_key);
  66. break;
  67. default:
  68. throw new Exception('Unknown property '.$name);
  69. }
  70. }
  71. public function __set(string $name, $val){
  72. switch($name){
  73. case 'id':case 'name':
  74. throw new Exception('Property '.$name.' is read only');
  75. break;
  76. default:
  77. throw new Exception('Unknown property '.$name);
  78. }
  79. }
  80. public function __call(string $name, array $args){
  81. switch($name){
  82. default:
  83. throw new Exception('Method '.$name.' not implemented');
  84. }
  85. }
  86. public static function __callStatic(string $name, array $args){
  87. throw new Exception('Static method '.$name.' not implemented');
  88. }
  89. public function __sleep(){
  90. $this->save();
  91. }
  92. public function __wakeup(){
  93. $this->reload(true);
  94. }
  95. public function __toString(){
  96. return $this->name.'('.$this->id.')';
  97. }
  98. public function __invoke(){
  99. return $this->_data;
  100. }
  101. public function __clone(){
  102. unset($this->$_data[self::$primary_key]);
  103. }
  104. // JsonSerializable
  105. public function jsonSerialize(){
  106. return $this->_data;
  107. }
  108. // ArrayAccess
  109. public function offsetSet($key, $val){
  110. $this->set($key, $val);
  111. }
  112. public function offsetExists($key){
  113. return $this->has($key);
  114. }
  115. public function offsetUnset($key){
  116. return $this->unset($key);
  117. }
  118. public function offsetGet($key){
  119. return $this->get($key);
  120. }
  121. // Main API
  122. public static function bind(SQL $sql){
  123. self::$sql = $sql;
  124. // @todo handle updating live instances
  125. }
  126. public static function query(...$args){
  127. return self::$sql->query(...$args);
  128. }
  129. // Instance Api
  130. public function values($values){
  131. foreach($values as $key => $val){
  132. $this->set($key, $val);
  133. }
  134. return $this;
  135. }
  136. public function load(bool $force = false){
  137. if(!$force && $this->dirty()){
  138. throw new Exception('Cannot load, there are pending changes');
  139. }else{
  140. if(!is_null($this->id)){
  141. $data = self::query(
  142. "select * " .
  143. "from {$this->name} ".
  144. "where ".self::$primary_key." = ?",
  145. 'i',
  146. $this->id
  147. )->assoc_result;
  148. if($data === false){
  149. throw new Exception("{$this->name} with ".self::$primary_key." of {$this->id} does not exist");
  150. }
  151. $this->_data = $data;
  152. }
  153. }
  154. return $this;
  155. }
  156. public function save(){
  157. if($this->dirty()){
  158. $data = [];
  159. $set = "set ";
  160. $types = '';
  161. foreach($this->_changed as $key){
  162. if(isset($this->_data[$key]) || is_null($this->_data[$key])){
  163. $data[$key] = $this->_data[$key];
  164. }else{
  165. $set .= "{$key} = null";
  166. }
  167. }
  168. foreach($data as $key => $val){
  169. if(is_string($val)){
  170. $types .= 's';
  171. }elseif(is_int($val)){
  172. $types .= 'i';
  173. }elseif(is_double($val)){
  174. $types .= 'd';
  175. }else{
  176. throw new Exception('Unknown data type');
  177. }
  178. $set .= "{$key} = ? ";
  179. }
  180. if(!is_null($this->id) && !in_array(self::$primary_key, $this->_changed)){
  181. $data = array_merge(array_values($data), [$this->id]);
  182. self::query(
  183. "update {$this->name} {$set} where ".self::primary_key." = ?",
  184. $types.'i',
  185. $data
  186. )->execute();
  187. }else{
  188. self::query(
  189. "insert {$this->name} {$set}"
  190. )->execute();
  191. $this->_data[self::$primary_key] = self::$sql->insert_id;
  192. }
  193. }
  194. // Always fetch again from the database in case saving
  195. // forces something to change at the database level
  196. return $this->reload(true);
  197. }
  198. public function reload(bool $force = false){
  199. if($force){
  200. $this->_changed = [];
  201. }
  202. return $this->load($force);
  203. }
  204. public function clear(){
  205. return $this->reload(true);
  206. }
  207. public function get($key){
  208. return $this->_data[$key];
  209. }
  210. public function set($key, $val){
  211. if($key === self::$primary_key && !is_null($this->id)){
  212. throw new Exception('You are not allowed to change the primary key');
  213. }
  214. $this->_data[$key] = $val;
  215. $this->_changed = array_merge($this->_changed, [$key]);
  216. return $this;
  217. }
  218. public function unset($key){
  219. unset($this->_data[$key]);
  220. return $this;
  221. }
  222. public function has($key){
  223. return isset($this->_data[$key]);
  224. }
  225. public function dirty(string $key = null){
  226. if(is_null($key)){
  227. return count($this->_changed) > 0;
  228. }else{
  229. return in_array($key, $this->_changed);
  230. }
  231. }
  232. public function release(){
  233. $this->__sleep();
  234. $this->_changed = [];
  235. $this->_data = [];
  236. }
  237. }
  238. ?>