/
Model.class.php
610 lines (512 loc) · 17.7 KB
/
Model.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
<?php
namespace Dbaser;
class Model extends Base {
static protected $primaryKey = 'id';
static protected $tableName = null; // override this if you want a different table name than the pluralized version of your class name
static protected $columns = ["*"]; // override this for speed performance
// relations: [propertyName => className]
static protected $hasOne = [];
static protected $hasMany = [];
static protected $manyToMany = [];
// when a manyToMany join should return extra columns
// [propertyName => [..cols...]]
static protected $richJoin = [];
// propertios to ignore when saving
static $readOnly = [];
protected function readOnly() {
// exclude relations as well...
// if not mysql with cry about invalid column references
return array_merge(
[ // default passive properties
static::$primaryKey,
'created_at',
'updated_at',
'isNew'
],
static::$readOnly, // user defined...
array_keys(static::$manyToMany)
);
}
// if the static var tableName isn't set, figure out based on conventions
// class names should be singular capitalized camelcase
// table names should be plural lowercase with underscores
static function tableName() {
if (static::$tableName) return static::$tableName;
$tname = get_called_class(); // get the class name
$tname = preg_replace("/(?<!^)([A-Z])/", "_$1", $tname); // convert camelcase to underscores
$tname = strtolower( $tname ); // all lowercase
return static::plural($tname); // return the plural version
}
// generate a query object that has the base columns and table select;
protected static function baseQuery() {
$tname = static::tableName();
$query = new Query($tname);
return $query->select([$tname => static::$columns]);
}
// =======================
// = Create a new record =
// =======================
static function create($params = array()) {
$class = get_called_class();
$obj = new $class($params);
$obj->save();
return $obj;
}
// ===============================
// = Delete record from database =
// ===============================
static function delete($id) {
$tname = static::tableName();
$query = new Query($tname);
$pk = static::$primaryKey;
$query->delete($tname)->where("`$tname`.`$pk` = ?", [$id]);
static::query($query, $query->params);
}
// ================================
// = Apply the options to a query =
// ================================
static protected function applyOptions(&$query, $options) {
if (isset($options['where'])) $query->where( $options['where'] );
if (isset($options['orderBy'])) $query->orderBy( $options['orderBy'], @$options['direction']);
if (isset($options['limit'])) $query->limit( $options['limit'] );
if (isset($options['offset'])) $query->offset( $options['offset'] );
}
// ======================
// = Return all records =
// ======================
static function all($opts = array()) {
$query = static::baseQuery();
self::setDefaults($opts, [
"direction" => [
'pattern' => "/ASC|DESC/i",
'value' => 'ASC'
]
]);
self::applyOptions($query, $opts);
$class = get_called_class();
$result = static::query(
$query,
$query->params,
function($row) use ($class) {
return new $class($row);
}
);
// if (count($result) == 1) $result = current($result);
return $result;
}
// =============================================
// = Find singular record based on primary key =
// =============================================
static function find($id) {
$query = static::baseQuery()->where("id = ?", [$id]);
$class = get_called_class();
$result = static::query(
$query,
$query->params,
function($row) use ($class) {
return new $class($row);
}
);
if (gettype($result) == "array")
return current($result);
return $result;
}
// =======================
// = Search for a record =
// =======================
static function search($colvals = array(), $opts = array()) {
$query = static::baseQuery();
$tname = static::tableName();
self::setDefaults($opts, [
"limit" => ["pattern" => "/\d+/"]
]);
foreach ($colvals as $col => &$val) {
if (!strstr($val, "%")) // if they didn't define wildcards themselves...
$val = "%$val%"; // add the wildcards
$query->where("`$tname`.`$col` LIKE ?", [$val]); // append the filter
}
if (isset($opts['limit'])) {
$query->limit($opts['limit']); // if limit is set, limit it.
}
$class = get_called_class();
return static::query($query, $query->params, function($row) use ($class) {
return new $class($row);
});
}
// ==============================================
// = Find where column name (equals/sign) value =
// ==============================================
static function findByName($array, $opts = array()) {
// set up the default options
self::setDefaults($opts, [
"sign" => ["value" => "=", "pattern" => "/^(=|<|>|LIKE)+$/"],
"limit" => ["pattern" => "/\d+/"]
]);
$class = get_called_class();
$query = static::baseQuery();
foreach ($array as $col => $val) {
$query->where("`".static::tableName()."`.$col {$opts['sign']} ?", [$val]);
}
self::applyOptions($query, $opts);
$result = static::query(
$query,
$query->params,
function($row) use ($class) {
return new $class($row);
}
);
// foreach ($result as &$obj) $obj = new $class($obj);
return $result;
}
// =================
// = Select random =
// =================
static function random($options = array()) {
$query = static::baseQuery();
$class = get_called_class();
if (isset($options['where'])) $query->where($options['where']);
$query->orderBy("RAND()");
if (isset($options['limit'])) $query->limit($options['limit']);
if (isset($options['offset'])) $query->offset($options['offset']);
$result = static::query(
$query,
$query->params,
function($row) use ($class) {
return new $class($row);
}
);
if (count($result) == 1)
return current($result);
return $result;
}
// ============================
// = Starting with a somthing =
// ============================
static function startingWith($prop, $letter) {
return static::findByName([$prop => "$letter%"], ['sign' => "LIKE"]);
}
// =================================================
// = Generate an array of objects based on raw SQL =
// =================================================
static function fromSQL($sql, $params = array(), $dataTypes = null) {
$class = get_called_class();
return static::query(
$sql,
$params,
function($row) use ($class) {
return new $class($row);
},
$dataTypes
);
}
// ==============================
// = info based static methods: =
// ==============================
// return the number of records in a table
static function records() {
$tname = static::tableName();
$pk = static::$primaryKey;
return current(current(static::query("SELECT COUNT(`$tname`.`$pk`) AS count FROM `$tname`;")));
}
// where column (condition) value
static function count($condition) {
$tname = static::tableName();
$pk = static::$primaryKey;
return current(current(static::query(
"SELECT COUNT(`$tname`.`$pk`) AS count FROM `$tname`
WHERE $condition;"
)));
}
// ===================
// = get by relation =
// ===================
static function byRelation($model, $pkValue = null, $options = array()) {
$class = get_called_class();
$options = self::setDefaults($options, [
"direction" => [
'pattern' => "/ASC|DESC/i",
'value' => 'ASC'
],
"limit" => ['pattern' => "/^\d+$/"],
"offset" => ['pattern' => "/^\d+$/"]
]);
// if a model object is passed in, we can extrapolate the values from that.
if ($model instanceof Dbaser\Model) {
$model = $model->className;
$pkValue = $model->{$model::$primaryKey};
}
// in the case of a many to many relation
if (in_array($model, static::$manyToMany)) {
$joint = static::tableJoin(static::tableName(), $model::tableName());
$query = new Query($joint); // query from the joint table
$query->select([static::tableName() => static::$columns]); // select only the columns from this class
$t = static::tableName();
$pk = static::$primaryKey;
$query
->join("INNER JOIN `$t` ON `$joint`.`$t` = `$t`.`$pk`") // join the requested class on the join table based on primary key
->where("`$joint`.`{$model::tableName()}` = ?", [$pkValue]); // limit to the primary key of relation
// run the query and get back a 2d array
self::applyOptions($query, $options);
return $model::query(
$query,
$query->params,
function($row) use ($class) {
return new $class($row);
}
);
}
if (in_array($class, $model::$hasMany)) {
return static::findByName([static::singular($model) => $pkValue], $options);
}
if (in_array($class, $model::$hasOne)) {
$proxy = new $model([$model::$primaryKey => $pkValue]); // create an object of type relation
$prop = array_search($class, $model::$hasOne);
return $proxy->$prop; // ask the model for it's relation of this class's type
}
// at this point all else has failed.
return false;
}
// ====================
// = Get the last row =
// ====================
static function last() {
$query = static::baseQuery()
->orderBy(static::$primaryKey, "DESC")
->limit(1);
$class = get_called_class();
$result = static::query(
$query,
$query->params,
function($row) use ($class) {
return new $class($row);
}
);
if (gettype($result) == "array")
return current($result);
return $result;
}
static function lastKey() {
$tname = static::tableName();
$query = new Query($tname);
$query->select([$tname => [static::$primaryKey]])
->orderBy(static::$primaryKey, "DESC")
->limit(1);
$result = static::query($query, $query->params);
if (count($result) > 0)
return current($result)[static::$primaryKey];
return false;
}
///////////////////// ====================== //////////////////////////
///////////////////// = end static methods = //////////////////////////
///////////////////// ====================== //////////////////////////
private
$isNew = true; // tracks the new status of record
function __construct($vars = array()) {
foreach ($vars as $property => $value) {
if (!isset(static::$hasOne[$property])) $this->$property = $value; // load all of the properties
}
if (isset($this->{static::$primaryKey})) $this->isNew = false; // update the status of isNew...
}
// ====================
// = Relation methods =
// ====================
// override the get function to catch and initialize relation properties
function __get($prop) {
// if ($value = parent::__get($prop)) return $value;
// lazy load relations
if ( isset(static::$hasOne[$prop]) && !isset($this->$prop) ) $this->hasOne($prop);
( isset(static::$richJoin[$prop]) ) ? $extraCols = (array) static::$richJoin[$prop] : $extraCols = [];
if ( isset(static::$manyToMany[$prop]) && !isset($this->$prop) ) $this->manyToMany($prop, $extraCols);
if ( isset(static::$hasMany[$prop]) && !isset($this->$prop) ) $this->hasMany($prop);
return parent::__get($prop);
}
protected function hasOne($prop) {
$className = static::$hasOne[$prop];
$foreignTable = $className::tableName();
$fkColumn = static::singular($className::tableName());
$query = $className::baseQuery();
$query->join("INNER JOIN `$this->tableName` ON `$this->tableName`.`$fkColumn` = `$foreignTable`.`{$className::$primaryKey}`");
$query->where("`$this->tableName`.`$this->primaryKeyName` = ?", [$this->primaryKey]);
$query->limit(1);
$foreignObject = $className::query($query, $query->params, function($row) use ($className) {
return new $className($row);
});
if (empty($foreignObject)) {
$this->$prop = null;
} else {
$this->$prop = current($foreignObject);
}
}
protected function hasMany($prop) {
if (gettype(static::$hasMany[$prop]) == 'array') {
$className = static::$hasMany[$prop]['class'];
if (isset(static::$hasMany[$prop]['options'])) {
$options = self::setDefaults(static::$hasMany[$prop]['options'], [
"direction" => [
'pattern' => "/ASC|DESC/i",
'value' => 'ASC'
],
"limit" => ['pattern' => "/^\d+$/"],
"offset" => ['pattern' => "/^\d+$/"]
]);
}
} else {
$className = static::$hasMany[$prop];
}
$foreignTable = $className::tableName();
// select from the foreign table
$query = new Query($foreignTable);
// column name in foreign table is singular...
$cname = static::singular(static::tableName());
// get a 2d array where the primary key matches the value of this objcet's primary key
$query
->select([$foreignTable => $className::$columns])
->where("`$foreignTable`.`$cname` = ?", [$this->{static::$primaryKey}]);
self::applyOptions($query, $options);
$this->$prop = $className::query(
$query,
$query->params,
function($row) use ($className) {
return new $className($row);
}
);
}
protected function manyToMany($prop, $extraColumns = array()) {
$options = [];
if (gettype(static::$manyToMany[$prop]) == 'array') {
$className = static::$manyToMany[$prop]['class'];
if (isset(static::$manyToMany[$prop]['options'])) {
$options = static::$manyToMany[$prop]['options'];
}
} else {
// get classname defined in the static $manyToMany (k/v) array
$className = static::$manyToMany[$prop];
}
self::setDefaults($options, [
"direction" => [
'pattern' => "/ASC|DESC/i",
'value' => 'ASC'
],
"limit" => ['pattern' => "/^\d+$/"],
"offset" => ['pattern' => "/^\d+$/"]
]);
$foreignTable = $className::tableName();
// get the proper order of tables as per naming convention for join table.
$joint = static::tableJoin($this->tableName, $foreignTable);
// query from the joint table
$query = new Query($joint);
// select only the columns from requested class
$select = [$foreignTable => $className::$columns];
if (!empty($extraColumns)) {
$select[$joint] = $extraColumns; // add in additional columns
static::$readOnly = array_merge(static::$readOnly, $extraColumns); // don't save these
}
$query->select($select);
// join the requested class on the join table based on primary key
$query->join("INNER JOIN `{$className::tableName()}` ON `$joint`.`{$className::tableName()}` = `{$className::tableName()}`.`{$className::$primaryKey}`");
// limit to the primary key of this table
$query->where("`$joint`.`$this->tableName` = ?", [$this->primaryKey]);
// run the query and get back a 2d array, set to the requested prop
self::applyOptions($query, $options);
$this->$prop = new ModelCollection(
$className::query(
$query,
$query->params,
function ($row) use ($className) {
return new $className($row);
}
),
$this
);
}
function load ($propertyName) {
return (bool) $this->$propertyName;
}
// ========================
// = end relation methods =
// ========================
// return properties as array
function toArray() {
$properties = [];
foreach ($this as $prop => $value) {
if (!in_array($prop, $this->readOnly())) {
if ($value instanceof Model) {
$properties[$prop] = $value->primaryKey;
} else {
$properties[$prop] = $value;
}
}
}
return $properties;
}
function isNew() {
if (isset($this->{static::$primaryKey})) return false;
return $this->isNew;
}
function save($sync = true) {
// insert if new
if ($this->isNew())
return $this->insert($sync);
$query = new Query($this->tableName);
$query->update($this->tableName, $this->toArray())->where($this->primaryKeyName.' = ?', [$this->primaryKey])->limit(1);
$result = static::query($query, $query->params);
if ($sync) $this->sync();
return (bool) $result;
}
// =====================================================
// = Sync the object properties to the database values =
// =====================================================
function sync() {
if ($this->isNew()) return false;
$query = static::baseQuery()->where("$this->primaryKeyName = ?", [$this->primaryKey]);
$params = current(static::query($query, $query->params));
foreach ($params as $key => $param) $this->$key = $param;
}
protected function insert($sync = true) {
$tname = static::tableName();
$properties = $this->toArray();
if (count($properties) < 1) $properties[static::$primaryKey] = null;
$query = new Query($tname);
$query->insert($tname, $properties);
$pk = static::query($query, $query->params); // could return error;
$this->id = $pk;
if ($sync)
$this->sync();
return true;
}
function destroy() {
if ($this->isNew()) return false;
static::delete($this->id);
$this->id = null;
}
function __toString() {
return print_r($this, true);
}
// =====================================
// = Query options resolution function =
// =====================================
// accepts an array of names,
// each containing a default value and
// regex matching pattern for validation;
protected static function setDefaults(&$options, $defaults) {
foreach ($defaults as $name => $default) {
if (isset($options[$name])) {
if (isset($default['pattern'])) {
if (!preg_match($default['pattern'], $options[$name]))
unset($options[$name]);
}
} else {
if (isset($default['value']))
$options[$name] = $default['value'];
}
}
return $options;
}
// ===========
// = Getters =
// ===========
// these are automatically computed when requesting the camel-case property name ( getThingName : $obj->thingName )
function getPrimaryKey () { return $this->{$this::$primaryKey}; }
function getPrimaryKeyName () { return $this::$primaryKey; }
function getTableName () { return $this->tableName(); }
}