orm.abstract.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 fetch(array $filter = null, int $start = null, int $amount = null){
  232. $results = [];
  233. self::each_where(function($item) use($results){
  234. $results[] = $item;
  235. }, $filter, $start, $amount);
  236. return $results;
  237. }
  238. public static function str_replace_first($search, $replace, $source) {
  239. $explode = explode($search, $source);
  240. $shift = array_shift($explode);
  241. $implode = implode($search, $explode);
  242. return $shift.$replace.$implode;
  243. }
  244. // Instance Api
  245. public function values($values){
  246. foreach($values as $key => $val){
  247. $this->set($key, $val);
  248. }
  249. return $this;
  250. }
  251. public function load(bool $force = false){
  252. if(!$force && $this->dirty()){
  253. throw new Exception('Cannot load, there are pending changes');
  254. }else{
  255. if(!is_null($this->id)){
  256. $data = self::query(
  257. "select * " .
  258. "from {$this->name} ".
  259. "where ".static::$primary_key." = ?",
  260. 'i',
  261. $this->id
  262. )->assoc_result;
  263. if($data === false){
  264. throw new Exception("{$this->name} with ".static::$primary_key." of {$this->id} does not exist");
  265. }
  266. $this->_data = $data;
  267. }
  268. }
  269. return $this;
  270. }
  271. public function save(){
  272. if($this->dirty()){
  273. $data = [];
  274. $set = "set ";
  275. $types = '';
  276. foreach($this->_changed as $key){
  277. if(isset($this->_data[$key]) || is_null($this->_data[$key])){
  278. $data[$key] = $this->_data[$key];
  279. }else{
  280. $set .= "{$key} = null";
  281. }
  282. }
  283. foreach($data as $key => $val){
  284. if(is_string($val)){
  285. $types .= 's';
  286. }elseif(is_double($val)){
  287. $types .= 'd';
  288. }elseif(is_int($val)){
  289. $types .= 'i';
  290. }else{
  291. throw new Exception('Unknown data type');
  292. }
  293. $set .= "{$key} = ? ";
  294. }
  295. if(!is_null($this->id) && !in_array(static::$primary_key, $this->_changed)){
  296. $data = array_merge(array_values($data), [$this->id]);
  297. self::query(
  298. "update {$this->name} {$set} where ".static::$primary_key." = ?",
  299. $types.'i',
  300. $data
  301. )->execute();
  302. }else{
  303. self::query(
  304. "insert {$this->name} {$set}"
  305. )->execute();
  306. $this->_data[static::$primary_key] = self::$sql->insert_id;
  307. }
  308. }
  309. // Always fetch again from the database in case saving
  310. // forces something to change at the database level
  311. return $this->reload(true);
  312. }
  313. public function reload(bool $force = false){
  314. if($force){
  315. $this->_changed = [];
  316. }
  317. return $this->load($force);
  318. }
  319. public function clear(){
  320. return $this->reload(true);
  321. }
  322. public function get($key){
  323. return $this->_data[$key];
  324. }
  325. public function set($key, $val){
  326. if($key === static::$primary_key && !is_null($this->id)){
  327. throw new Exception('You are not allowed to change the primary key');
  328. }
  329. $this->_data[$key] = $val;
  330. $this->_changed = array_merge($this->_changed, [$key]);
  331. return $this;
  332. }
  333. public function unset($key){
  334. unset($this->_data[$key]);
  335. return $this;
  336. }
  337. public function has($key){
  338. return isset($this->_data[$key]);
  339. }
  340. public function dirty(string $key = null){
  341. if(is_null($key)){
  342. return count($this->_changed) > 0;
  343. }else{
  344. return in_array($key, $this->_changed);
  345. }
  346. }
  347. public function related(string $name){
  348. if(isset($this->_related[$name])){
  349. return $this->_related[$name];
  350. }else{
  351. $class = "Model\\{$name}";
  352. if(self::$aliases['belongs_to'][$name]){
  353. $this->_related[$name] = $class::fetch([static::$foreign_key => $this->id]);
  354. }elseif(self::$aliases['has_one'][$name]){
  355. $this->_related[$name] = $class::fetch([$this->name.static::$foreign_key_suffix => $this->id]);
  356. }elseif(self::$aliases['has_many'][$name]){
  357. //$this->_related[$name] = $class::fetch([$this->name.static::$foreign_key_suffix => $this->id]);
  358. throw new Exception("has_many relationships are not implemented yet");
  359. }
  360. }
  361. if(isset($this->_related[$name])){
  362. return $this->_related[$name];
  363. }else{
  364. throw new Exception("Relationship {$name} does not exist");
  365. }
  366. }
  367. }
  368. ?>