orm.abstract.class.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 $instances = [];
  16. private static $sql;
  17. protected static $name = null;
  18. // Magic functions
  19. private function __construct($idOrData){
  20. if(!isset(self::$aliases[$this->name])){
  21. foreach(static::$belongs_to as $alias => $details){
  22. self::$aliases[$this->name]['belongs_to'][$alias] = array_merge(
  23. [
  24. 'model'=>$alias,
  25. 'foreign_key'=>$alias.static::$foreign_key_suffix
  26. ],
  27. $details
  28. );
  29. }
  30. foreach(static::$has_one as $alias => $details){
  31. self::$aliases[$this->name]['has_one'][$alias] = array_merge(
  32. [
  33. 'model'=>$alias,
  34. 'foreign_key'=>$alias.static::$foreign_key_suffix
  35. ],
  36. $details
  37. );
  38. }
  39. foreach(static::$has_many as $alias => $details){
  40. self::$aliases[$this->name]['has_many'][$alias] = array_merge(
  41. [
  42. 'model'=>$alias,
  43. 'foreign_key'=>$alias.static::$foreign_key_suffix,
  44. 'through'=> null
  45. ],
  46. $details
  47. );
  48. }
  49. }
  50. // Clear relationship definitions to save memory
  51. static::$belongs_to = static::$has_one = static::$has_many =null;
  52. if(is_array($idOrData)){
  53. if(isset($idOrData[static::$primary_key]) && self::cached($idOrData[static::$primary_key])){
  54. throw new Exception('Instance already cached');
  55. }
  56. foreach($idOrData as $key => $val){
  57. $this->_data[$key] = $val;
  58. }
  59. }else{
  60. if(self::cached($idOrData)){
  61. throw new Exception('Instance already cached');
  62. }
  63. $this->_data[static::$primary_key] = (int)$idOrData;
  64. }
  65. self::$instances[] = $this;
  66. }
  67. private function __destruct(){
  68. $this->__sleep();
  69. $this->_changed = [];
  70. $this->_data = [];
  71. $this->_related = [];
  72. $key = array_search(self::$instances, $this);
  73. if($key !== false){
  74. array_splice(self::$instances, $key, 1);
  75. }
  76. }
  77. public function __get(string $name){
  78. switch($name){
  79. case 'name':
  80. return static::name();
  81. break;
  82. case 'id':
  83. return $this->get(static::$primary_key);
  84. break;
  85. default:
  86. throw new Exception('Unknown property '.$name);
  87. }
  88. }
  89. public function __set(string $name, $val){
  90. switch($name){
  91. case 'id':case 'name':
  92. throw new Exception('Property '.$name.' is read only');
  93. break;
  94. default:
  95. throw new Exception('Unknown property '.$name);
  96. }
  97. }
  98. public function __sleep(){
  99. $this->save();
  100. }
  101. public function __wakeup(){
  102. $this->reload(true);
  103. }
  104. public function __toString(){
  105. return $this->name.'('.$this->id.')';
  106. }
  107. public function __invoke(){
  108. return $this->_data;
  109. }
  110. public function __clone(){
  111. unset($this->$_data[static::$primary_key]);
  112. }
  113. // JsonSerializable
  114. public function jsonSerialize(){
  115. return $this->_data;
  116. }
  117. // ArrayAccess
  118. public function offsetSet($key, $val){
  119. $this->set($key, $val);
  120. }
  121. public function offsetExists($key){
  122. return $this->has($key);
  123. }
  124. public function offsetUnset($key){
  125. return $this->unset($key);
  126. }
  127. public function offsetGet($key){
  128. return $this->get($key);
  129. }
  130. // Main API
  131. public static function name(){
  132. if(is_null(static::$name)){
  133. $name = get_called_class();
  134. static::$name = substr($name, strrpos($name, '\\') + 1);
  135. }
  136. return static::$name;
  137. }
  138. public static function bind(SQL $sql){
  139. self::$sql = $sql;
  140. // @todo handle updating live instances
  141. }
  142. public static function query(...$args){
  143. return self::$sql->query(...$args);
  144. }
  145. public static function instance(int $id){
  146. $instance = self::cached_instance($id);
  147. if(!is_null($instance)){
  148. return $instance;
  149. }elseif(self::exists($id)){
  150. return new static($id);
  151. }
  152. return null;
  153. }
  154. public static function exists(int $id){
  155. return (int)self::query(
  156. "select count(1) as count ".
  157. "from ".static::name().' '.
  158. "where ".static::$primary_key." = ?",
  159. 'i',
  160. $id
  161. )->assoc_result["count"] > 0;
  162. }
  163. public static function cached_instance(int $id){
  164. $name = static::name();
  165. if(isset(self::$instances[$name])){
  166. $instances = array_filter(self::$instances[$name], function(&$instance){
  167. return $instance->id === $id;
  168. });
  169. return isset($instances[0]) ? $instances[0] : null;
  170. }
  171. return null;
  172. }
  173. public static function cached(int $id){
  174. return !is_null(self::cached_instance($id));
  175. }
  176. public static function delete(int $id){
  177. $query = self::query(
  178. "delete from ".static::name().' '.
  179. "where ".static::$primary_key." = ?",
  180. 'i',
  181. $id
  182. );
  183. return $query->execute() && $query->affected_rows > 0;
  184. }
  185. public static function each_cached(callable $fn){
  186. $name = static::name();
  187. if(self::$instances[$name]){
  188. array_walk(self::$instances[$name], $fn);
  189. }
  190. }
  191. public static function each_where(callable $fn, array $filter = null, int $start = null, int $amount = null){
  192. $limit = ' ';
  193. if(!is_null($start) && !is_null($amount)){
  194. $limit .= "limit {$start}, {$amount}";
  195. }
  196. $where = ' ';
  197. $types = null;
  198. $bindings = null;
  199. if(!is_null($filter)){
  200. $types = '';
  201. $bindings = array();
  202. foreach($filter as $key => $val){
  203. if(is_string($val)){
  204. $types .= 's';
  205. }elseif(is_double($val)){
  206. $types .= 'd';
  207. }elseif(is_int($val)){
  208. $types .= 'i';
  209. }else{
  210. throw new Exception("Unknown data type");
  211. }
  212. $where .= 'and {$key} = ? ';
  213. $bindings[] = $val;
  214. }
  215. $where = self::str_replace_first(' and ', ' ', $where);
  216. }
  217. self::query(
  218. "select ".static::$primary_key.' id '.
  219. "from ".static::name().
  220. $where.
  221. $limit,
  222. $types,
  223. $bindings
  224. )->each_assoc(function($row) use($fn){
  225. $fn(self::instance((int)$row['id']));
  226. });
  227. }
  228. public static function each(callable $fn, int $start = null, int $amount = null){
  229. self::each_where($fn, null, $start, $amount);
  230. }
  231. public static function str_replace_first($search, $replace, $source) {
  232. $explode = explode($search, $source);
  233. $shift = array_shift($explode);
  234. $implode = implode($search, $explode);
  235. return $shift.$replace.$implode;
  236. }
  237. // Instance Api
  238. public function values($values){
  239. foreach($values as $key => $val){
  240. $this->set($key, $val);
  241. }
  242. return $this;
  243. }
  244. public function load(bool $force = false){
  245. if(!$force && $this->dirty()){
  246. throw new Exception('Cannot load, there are pending changes');
  247. }else{
  248. if(!is_null($this->id)){
  249. $data = self::query(
  250. "select * " .
  251. "from {$this->name} ".
  252. "where ".static::$primary_key." = ?",
  253. 'i',
  254. $this->id
  255. )->assoc_result;
  256. if($data === false){
  257. throw new Exception("{$this->name} with ".static::$primary_key." of {$this->id} does not exist");
  258. }
  259. $this->_data = $data;
  260. }
  261. }
  262. return $this;
  263. }
  264. public function save(){
  265. if($this->dirty()){
  266. $data = [];
  267. $set = "set ";
  268. $types = '';
  269. foreach($this->_changed as $key){
  270. if(isset($this->_data[$key]) || is_null($this->_data[$key])){
  271. $data[$key] = $this->_data[$key];
  272. }else{
  273. $set .= "{$key} = null";
  274. }
  275. }
  276. foreach($data as $key => $val){
  277. if(is_string($val)){
  278. $types .= 's';
  279. }elseif(is_double($val)){
  280. $types .= 'd';
  281. }elseif(is_int($val)){
  282. $types .= 'i';
  283. }else{
  284. throw new Exception('Unknown data type');
  285. }
  286. $set .= "{$key} = ? ";
  287. }
  288. if(!is_null($this->id) && !in_array(static::$primary_key, $this->_changed)){
  289. $data = array_merge(array_values($data), [$this->id]);
  290. self::query(
  291. "update {$this->name} {$set} where ".static::$primary_key." = ?",
  292. $types.'i',
  293. $data
  294. )->execute();
  295. }else{
  296. self::query(
  297. "insert {$this->name} {$set}"
  298. )->execute();
  299. $this->_data[static::$primary_key] = self::$sql->insert_id;
  300. }
  301. }
  302. // Always fetch again from the database in case saving
  303. // forces something to change at the database level
  304. return $this->reload(true);
  305. }
  306. public function reload(bool $force = false){
  307. if($force){
  308. $this->_changed = [];
  309. }
  310. return $this->load($force);
  311. }
  312. public function clear(){
  313. return $this->reload(true);
  314. }
  315. public function get($key){
  316. return $this->_data[$key];
  317. }
  318. public function set($key, $val){
  319. if($key === static::$primary_key && !is_null($this->id)){
  320. throw new Exception('You are not allowed to change the primary key');
  321. }
  322. $this->_data[$key] = $val;
  323. $this->_changed = array_merge($this->_changed, [$key]);
  324. return $this;
  325. }
  326. public function unset($key){
  327. unset($this->_data[$key]);
  328. return $this;
  329. }
  330. public function has($key){
  331. return isset($this->_data[$key]);
  332. }
  333. public function dirty(string $key = null){
  334. if(is_null($key)){
  335. return count($this->_changed) > 0;
  336. }else{
  337. return in_array($key, $this->_changed);
  338. }
  339. }
  340. }
  341. ?>