/
Model.class.php
600 lines (528 loc) · 15.8 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
<?php
Library::import('recess.lang.Inflector');
Library::import('recess.lang.RecessObject');
Library::import('recess.lang.RecessReflectionClass');
Library::import('recess.lang.Annotation');
Library::import('recess.database.Databases');
Library::import('recess.database.sql.ISqlConditions');
Library::import('recess.database.orm.ModelClassInfo');
Library::import('recess.database.sql.SqlBuilder');
Library::import('recess.database.orm.annotations.HasManyAnnotation', true);
Library::import('recess.database.orm.annotations.BelongsToAnnotation', true);
Library::import('recess.database.orm.annotations.DatabaseAnnotation', true);
Library::import('recess.database.orm.annotations.TableAnnotation', true);
Library::import('recess.database.orm.annotations.ColumnAnnotation', true);
Library::import('recess.database.orm.relationships.Relationship');
Library::import('recess.database.orm.relationships.HasManyRelationship');
Library::import('recess.database.orm.relationships.BelongsToRelationship');
/**
* Model is the basic unit of organization in Recess' simple ORM.
*
* @author Kris Jordan <krisjordan@gmail.com>
* @copyright 2008 Kris Jordan
* @package Recess! Framework
* @license MIT
* @link http://www.recessframework.org/
*/
abstract class Model extends RecessObject implements ISqlConditions {
/**
* Constructor can take either a keyed array or a string/int
* to set the primary key with;
*
* @param mixed $data
*/
public function __construct($data = null) {
if(is_numeric($data) || is_string($data)) {
$primaryKey = Model::primaryKeyName($this);
$this->$primaryKey = $data;
} else if (is_array($data)) {
$this->copy($data, false);
}
}
/**
* Get the datasource for a class.
*
* @param mixed $class
* @return ModelDataSource
*/
static function sourceFor($class) {
return self::getClassDescriptor($class)->getSource();
}
/**
* Get the name of the datasource for a class
*
* @param mixed $class
* @return string Key name of the ModelDataSource in Databases
*/
static function sourceNameFor($class) {
return self::getClassDescriptor($class)->getSourceName();
}
/**
* The table which $modelClass is persisted on.
*
* @param mixed $class
* @return string Table Name
*/
static function tableFor($class) {
return self::getClassDescriptor($class)->getTable();
}
/**
* Return the primary key column name for a class. This is prefixed
* with the class' table name.
*
* @param midex $class
* @return string Primary Key Column Name ie "table.id"
*/
static function primaryKeyFor($class) {
$descriptor = self::getClassDescriptor($class);
return $descriptor->getTable() . '.' . $descriptor->primaryKey;
}
/**
* Return the property name for the primary key.
*
* @param mixed $class
* @return string Primary key name ie: 'id'
*/
static function primaryKeyName($class) {
return self::getClassDescriptor($class)->primaryKey;
}
/**
* Get a relationship on a class or instance by the relationship's name.
*
* @param mixed $classOrInstance
* @param string $name of the relationship
* @return Relationship
*/
static function getRelationship($classOrInstance, $name) {
if(isset(self::getClassDescriptor($classOrInstance)->relationships[$name])) {
return self::getClassDescriptor($classOrInstance)->relationships[$name];
} else {
return false;
}
}
/**
* Return all relationships for a class or instance
*
* @param mixed $classOrInstance
* @return array of Relationship
*/
static function getRelationships($classOrInstance) {
return self::getClassDescriptor($classOrInstance)->relationships;
}
/**
* Retrieve an array of column names in the table corresponding to
* a model class.
*
* @param mixed $classOrInstance
* @return array of strings of column names
*/
static function getColumns($classOrInstance) {
return self::getClassDescriptor($classOrInstance)->columns;
}
/**
* Retrieve an array of the properties.
*
* @param mixed $classOrInstance
* @return array of type ModelProperty
*/
static function getProperties($classOrInstance) {
return self::getClassDescriptor($classOrInstance)->properties;
}
/**
* Implementation of the RecessObject abstract method. This method
* computes a static ModelDescriptor based on reflected meta data
* and annotations from the model class.
*
* @see RecessObject
* @param string $class
* @return ModelDescriptor
*/
static protected function buildClassDescriptor($class) {
$descriptor = new ModelDescriptor($class, false);
try {
$reflection = new RecessReflectionClass($class);
} catch(ReflectionException $e) {
throw new RecessException('Class "' . $class . '" has not been declared.', get_defined_vars());
}
$annotations = $reflection->getAnnotations();
foreach($annotations as $annotation) {
if($annotation instanceof ModelAnnotation) {
$annotation->massage($descriptor);
}
}
$reflectedProperties = $reflection->getProperties();
$properties = array();
foreach($reflectedProperties as $reflectedProperty) {
if(!$reflectedProperty->isStatic() && $reflectedProperty->isPublic()) {
$property = new ModelProperty();
$property->name = $reflectedProperty->name;
$annotations = $reflectedProperty->getAnnotations();
foreach($annotations as $annotation) {
if($annotation instanceof ModelPropertyAnnotation) {
$annotation->massage($property);
if($property->isPrimaryKey === true) {
$descriptor->primaryKey = $property->name;
}
}
}
$properties[] = $property;
}
}
$descriptor->properties = $properties;
$modelSource = Databases::getSource($descriptor->getSourceName());
$modelSource->cascadeTableDescriptor($descriptor->getTable(), $modelSource->modelToTableDescriptor($descriptor));
return $descriptor;
}
/**
* Attempt to generate a table from this model's descriptor.
*
* @param mixed $class
*/
static function createTableFor($class) {
$descriptor = self::getClassDescriptor($class);
$modelSource = Databases::getSource($descriptor->getSourceName());
$modelSource->exec($modelSource->createTableSql($descriptor));
}
/**
* Build a ModelSet from this instance by assigning this Model instance's
* properties and values.
*
* @return ModelSet
*/
protected function getModelSet() {
$thisClassDescriptor = self::getClassDescriptor($this);
$result = $thisClassDescriptor->getSource()->selectModelSet($thisClassDescriptor->getTable());
$pkName = self::primaryKeyName($this);
if(isset($this->$pkName)) {
$result = $result->equal($pkName,$this->$pkName);
} else {
foreach($this as $column => $value) {
if(isset($this->$column) && in_array($column,$thisClassDescriptor->columns)) {
$result = $result->assign($column, $value);
}
}
}
$result->rowClass = get_class($this);
return $result;
}
/**
* Return a results ModelSet based on the values of this instance's properties.
*
* @return ModelSet
*/
function select() {
return $this->getModelSet()->useAssignmentsAsConditions(true);
}
/**
* Alias for select.
*
* @return ModelSet
*/
function find() { return $this->select(); }
/**
* Select all. This is different from find() in that find will use
* assigned values to the model as equality statements.
*
* @return ModelSet
*/
function all() {
return $this->getModelSet();
}
/**
* Return a SqlBuilder object which has set the table and optionally
* assigned values to columns based on this instances' properties. This is used in
* insert(), update(), and delete()
*
* @param ModelDescriptor $descriptor
* @param boolean $useAssignment
* @param boolean $excludePrimaryKey
* @return SqlBuilder
*/
protected function assignmentSqlForThisObject(ModelDescriptor $descriptor, $useAssignment = true, $excludePrimaryKey = false) {
$sqlBuilder = new SqlBuilder();
$sqlBuilder->from($descriptor->getTable());
foreach($this as $column => $value) {
if($excludePrimaryKey && $descriptor->primaryKey == $column) continue;
if(in_array($column, $descriptor->columns) && isset($value)) {
if($useAssignment) {
$sqlBuilder->assign($column,$value);
} else {
$sqlBuilder->equal($column,$value);
}
}
}
return $sqlBuilder;
}
/**
* Delete row(s) from the data source which match this instance.
*
* @param boolean $cascade - Also delete models related to this model?
* @return boolean
*/
function delete($cascade = true) {
$thisClassDescriptor = self::getClassDescriptor($this);
if($cascade) {
foreach($thisClassDescriptor->relationships as $relationship) {
$relationship->delete($this);
}
}
$sqlBuilder = $this->assignmentSqlForThisObject($thisClassDescriptor, false);
return $thisClassDescriptor->getSource()->executeSqlBuilder($sqlBuilder, 'delete');
}
/**
* Insert row into the data source based on the values of this instance.
*
* @return boolean
*/
function insert() {
$thisClassDescriptor = self::getClassDescriptor($this);
$sqlBuilder = $this->assignmentSqlForThisObject($thisClassDescriptor);
$result = $thisClassDescriptor->getSource()->executeSqlBuilder($sqlBuilder, 'insert');
$primaryKey = $thisClassDescriptor->primaryKey;
$this->$primaryKey = $thisClassDescriptor->getSource()->lastInsertId();
return $result;
}
/**
* Update a row in the data source based on the values of this instance.
*
* @return boolean
*/
function update() {
$thisClassDescriptor = self::getClassDescriptor($this);
$sqlBuilder = $this->assignmentSqlForThisObject($thisClassDescriptor, true, true);
$primaryKey = $thisClassDescriptor->primaryKey;
$sqlBuilder->equal($thisClassDescriptor->primaryKey, $this->$primaryKey);
return $thisClassDescriptor->getSource()->executeSqlBuilder($sqlBuilder, 'update');
}
/**
* Insert or update depending on whether or not this instance's primary key is set.
*
* @return boolean
*/
function save() {
if($this->primaryKeyIsSet()) {
return $this->update();
} else {
return $this->insert();
}
}
/**
* @return boolean
*/
function primaryKeyIsSet() {
$thisClassDescriptor = self::getClassDescriptor($this);
$primaryKey = $thisClassDescriptor->primaryKey;
if(isset($this->$primaryKey)) {
return true;
} else {
return false;
}
}
/**
* Shortcut method which will determine whether a row
* with the current instances properties exists. If so, it will
* preload those values (side effects).
*
* Usage:
* $model->id = 1;
* if($model->exists()) {
* die('a lonesome death');
* }
*
* @return boolean
*/
function exists() {
$result = $this->select()->first();
if($result !== false) {
$this->copy($result, false);
return true;
} else {
return false;
}
}
/**
* Copy values from a key/value array or another model/object
* to this instance.
*
* @param iterable $keyValuePair
* @return Model
*/
function copy($keyValuePair, $excludePrimaryKey = true) {
if($excludePrimaryKey) {
$pk = Model::primaryKeyName($this);
}
foreach($keyValuePair as $key => $value) {
if($excludePrimaryKey && $key == $pk) {
continue;
}
$this->$key = $value;
}
return $this;
}
/**
* Add equality criteria between a column and value
*
* @param string $lhs Column
* @param mixed $rhs Value
* @return PdoDataSet
*/
function equal($column, $rhs){ return $this->select()->equal($column, $rhs); }
/**
* Add inequality criteria between a column and value
*
* @param string $lhs Column
* @param mixed $rhs Value
* @return PdoDataSet
*/
function notEqual($column, $rhs) { return $this->select()->notEqual($column,$rhs); }
/**
* Add criteria to state a column's value falls between $small and $big
*
* @param string $column Column
* @param mixed $small Floor Value
* @param mixed $big Ceiling Value
* @return PdoDataSet
*/
function between ($column, $small, $big) { return $this->select()->between($column, $small, $big); }
/**
* SQL criteria specifying a column's value is greater than $rhs
*
* @param string $column Column
* @param mixed $rhs Value
* @return PdoDataSet
*/
function greaterThan($column, $rhs) { return $this->select()->greaterThan($column,$rhs); }
/**
* SQL criteria specifying a column's value is no less than $rhs
*
* @param string $column Column
* @param mixed $rhs Value
* @return PdoDataSet
*/
function greaterThanOrEqualTo($column, $rhs) { return $this->select()->greaterThanOrEqualTo($column,$rhs); }
/**
* SQL criteria specifying a column's value is less than $rhs
*
* @param string $column Column
* @param mixed $rhs Value
* @return PdoDataSet
*/
function lessThan($column, $rhs) { return $this->select()->lessThan($column,$rhs); }
/**
* SQL criteria specifying a column's value is no greater than $rhs
*
* @param string $column Column
* @param mixed $rhs Value
* @return PdoDataSet
*/
function lessThanOrEqualTo($column, $rhs) { return $this->select()->lessThanOrEqualTo($column,$rhs); }
/**
* SQL LIKE criteria, note this does not automatically include wildcards
*
* @param string $column Column
* @param mixed $rhs Value
* @return PdoDataSet
*/
function like($column, $rhs) { return $this->select()->like($column,$rhs); }
/**
* SQL NOT LIKE criteria, note this does not automatically include wildcards
*
* @param string $column Column
* @param mixed $rhs Value
* @return PdoDataSet
*/
function notLike($column, $rhs) { return $this->select()->notLike($column,$rhs); }
}
/**
* Class descriptor + metadata for a model.
*/
class ModelDescriptor extends RecessObjectDescriptor {
public $primaryKey = 'id';
private $table;
public $plural;
public $modelClass;
public $relationships;
public $columns;
public $properties;
public $source;
function __construct($class, $loadColumns = true) {
$this->table = strtolower($class);
$this->relationships = array();
$this->properties = array();
$this->source = false;
if($loadColumns) {
$this->columns = $this->getSource()->getColumns($this->table);
} else {
$this->columns = array();
}
$this->primaryKeyColumn = 'id';
$this->modelClass = $class;
}
function __set_state($array) {
$descriptor = new ModelDescriptor($array['modelClass']);
$descriptor->primaryKey = $array['primaryKey'];
$descriptor->table = $array['table'];
$descriptor->relationships = $array['relationships'];
$descriptor->columns = $array['columns'];
$descriptor->properties = $array['properties'];
$descriptor->source = $array['source'];
$descriptor->attachedMethods = $array['attachedMethods'];
return $descriptor;
}
function setTable($table, $loadColumns = true) {
$this->table = $table;
if($loadColumns) {
$source = $this->getSource();
if(isset($source)) {
$this->columns = $this->getSource()->getColumns($this->table);
} else {
throw new RecessException('Data Source "' . $this->getSourceName() . '" is not set.', array());
}
} else {
$this->columns = array();
}
}
function getTable() {
return $this->table;
}
function setSource($source) {
$this->source = $source;
}
function getSource() {
if(!$this->source) {
return Databases::getDefaultSource();
} else {
return Databases::getSource($this->source);
}
}
function getSourceName() {
if(!$this->source) {
return 'Default';
} else {
return $this->source;
}
}
}
/**
* The data structure for a propery on a model
*/
class ModelProperty {
public $name;
public $type;
public $pkCallback;
public $isAutoIncrement = false;
public $isPrimaryKey = false;
public $isForeignKey = false;
public $required = false;
function __set_state($array) {
$prop = new ModelProperty();
$prop->name = $array['name'];
$prop->type = $array['type'];
$prop->pkCallback = $array['pkCallback'];
$prop->isAutoIncrement = $array['autoincrement'];
$prop->isPrimaryKey = $array['isPrimaryKey'];
$prop->isForeignKey = $array['isForeignKey'];
return $prop;
}
}
?>