-
Notifications
You must be signed in to change notification settings - Fork 1
/
MyActiveRecord.class.php
1124 lines (1031 loc) · 33.6 KB
/
MyActiveRecord.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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* MyActiveRecord
*
* A simple, speedy Object/Relational Mapper for MySQL based on Martin
* Fowler's ActiveRecord pattern and heavily influenced by the implementation
* of the same name in Ruby on Rails.
*
* Features
*
* - Mapping of table to class and row to object
* - Relationship retrieval
* - Data validation and error handling
* - PHP5 and PHP4 compatibility
*
* Limitations
*
* This class acheives simplicty of use and implementation through the
* following 'by-design' limitations:
*
* 1. This class talks to MySQL only.
*
* 2. Table/Class mapping is achieved by each database table being named
* IDENTICALLY to the MyActiveRecord subclass that will represent it
* (but in lowercase for compatibility reasons).
*
* 3. Every database table mapped by MyActiveRecord MUST have an
* autoincrementing primary-key named `id`.
*
*
* @category Database
* @package MyActiveRecord
* @author Ramon Antonio Parada <[email protected]>
* @author Jake Grimley <[email protected]>
* @copyright 2006 Jake Grimley
* @copyright 2012 Ramon Antonio Parada
* @version 0.5
*/
class MyActiveRecord {
public static $prefix = '';
public static $table;
/**
* A static method for preparing SQL queries. Safely escapes query paramaters
* using standard printf syntax, e.g.:
* <code>
* $sql = MyActiveRecord::Prepare("SELECT * FROM person WHERE last = '%s' AND age=%d", $_GET['lastname'], $_GET['age']);
* $people = MyActiveRecord::FindBySql('Person', $sql);
* </code>
*
* @static
* @param string sql A raw sql statement containing formatting
* @param mxd Args multiple arguments to be substituted into arguments. See sprintf documentation.
* @return string escaped sql string
*/
public static function Prepare() {
$args = func_get_args();
$rawsql = array_shift($args);
if( get_magic_quotes_gpc() ) $args = array_map( 'stripslashes', $args );
$args = array_map( 'mysql_escape_string', $args );
$sql = vsprintf($rawsql, $args);
return $sql;
}
/**
* Execute a SQL Query using Connection()
*
* @static
* @param string strSQL A SQL statement
* @return resource A MySQL result resource. False on failure.
*/
public static function Query($strSQL) {
$db =& Database::getInstance();
if( $rscResult = $db->query($strSQL) ) {
// return result
return $rscResult;
} else {
// fail
throw new Exception("MyActiveRecord::Query() - query failed: $strSQL with error: ".$db->error(), E_USER_WARNING);
//return false;
}
}
/**
* return a date formatted for the database
* @static
* @param int intTimeStamp A unix timestamp
* @return string mysql format date string
*/
public static function DbDate($intTimeStamp=null) {
return date('Y-m-d', $intTimeStamp ? $intTimeStamp:mktime() );
}
/**
* return a datetime formatted for the database
* @static
* @param int intTimeStamp A unix timestamp
* @return string mysql format datetime string
*/
public static function DbDateTime($intTimeStamp=null) {
return date('Y-m-d H:i:s', $intTimeStamp ? $intTimeStamp:mktime() );
}
/**
* return a unix timestamp from a database field
* @static
* @param string mysql datetime
* @return int unix timestamp
*/
public static function TimeStamp($strMySQLDate) {
return strtotime($strMySQLDate);
}
/**
* return an array containing names of tables in database
* @static
* @return array names of tables in database
*/
public static function Tables() {
$db =& Database::getInstance();
static $tables = array();
if( !count($tables) ) {
$result = MyActiveRecord::Query('SHOW TABLES')
or trigger_error('MyActiveRecord::Tables() - Cannot list tables', E_USER_ERROR);
while( $row = $db->fetch_row($result) ) {
$tables[]=$row[0];
}
}
return $tables;
}
/**
* checks to see if strTable exists in database returning true or false
* @static
* @param string strTable name of table to check for
* @return bool true/false
*/
public static function TableExists($strTable) {
return in_array( $strTable, MyActiveRecord::Tables() );
}
/**
* gets table representing class in database
* @static
* @param mixed $mxd either a string(class name) or an object
* @return string name of table in database representing class(string) or object
* false if no table found
*/
public static function Class2Table($mxd) {
$origClass = is_object($mxd) ? get_class($mxd) : $mxd;
if (isset(static::$table)) {
// return static::$table;
}
if (!class_exists($origClass)) {
throw new Exception("MyActiveRecord::Class2Table - Class $origClass does not exist");
}
$class = $origClass;
$existe = false;
while ( !$existe && ($class !='MyActiveRecord') ) {
$table = strtolower($class);
$existe = MyActiveRecord::TableExists( strtolower($class));
if (!$existe) {
$table = strtolower(MyActiveRecord::$prefix."_".$class);
$existe = MyActiveRecord::TableExists( strtolower($class));
}
if (!$existe) {
$class = get_parent_class($class);
}
}
if ($table == 'myactiverecord') {
throw new Exception("MyActiveRecord::Class2Table - Class $origClass does not have a table representation");
return false;
} else {
static::$table = $table;
}
return $table;
}
/**
* Returns an array describing the specified table, or false if the table
* does not exist in the database.
* The array contains one array per database column, keyed by the column
* name. To see the structure of the array you could try:
* <code>
* print_r( MyActiveRecord::Columns('your_table') );
* </code>
*
* @static
* @param string strTable The name of the database table
* @return array Table columns. False if the table does not exist.
*/
public static function Columns($strTable) {
$db =& Database::getInstance();
$strTable = MyActiveRecord::class2Table($strTable);
// cache results locally
static $cache=array(); //TODO variable estatica?
// already cached? return columns array
if( isset($cache[$strTable]) ) {
return $cache[$strTable];
} else {
// connect to database and run 'describe' query to get results
if( $rscResult = MyActiveRecord::Query("SHOW COLUMNS FROM $strTable") ) {
$arrFields = array();
while( $col = $db->fetch_assoc($rscResult) ) {
$arrFields[$col['Field']] = $col;
}
$db->free_result($rscResult);
// cache results for future use and return
return $cache[$strTable] = $arrFields;
} else {
throw new Exception("MyActiveRecord::Columns() - could not decribe table $strTable");
return false;
}
}
}
/**
* Gets the 'type' of a specific field in a specified table
* (i.e 'int'|'float'|'date'|'char'|'text')
*
* @static
* @param string strTable Name of database table
* @param string strField Name of field in table
* @return string Field type (e.g. 'int'|'float'|'date'|'char'|'text' ).
* False if not found.
*/
public static function GetType($strTable, $strField) {
$fields = MyActiveRecord::Columns($strTable);
if( isset($fields[$strField]['Type']) ) {
$type_len = explode( '(', $fields[$strField]['Type'] );
$type = $type_len[0];
return $type;
} else {
return false;
}
}
/**
* gets the maximum allowed length of a specified field in a specified
* table
*
* @static
* @param string strTable Name of database table
* @param string strField Name of field in table
* @return integer Maximum length of field. False if not found.
*/
public static function GetLen($strTable, $strField) {
$fields=MyActiveRecord::Columns($strTable);
if ( isset($fields[$strField]['Type']) ) {
$type_len = explode( '(', $fields[$strField]['Type'] );
$length = array_key_exists(1, $type_len) ? str_replace(')', '', $type_len[1]) : false;
return $length;
} else {
return false;
}
}
/**
* finds out whether a NULL value is allowed in a specified field in a
* specified table
*
* @static
* @param string strTable Name of database table
* @param string strField Name of field in table
* @return boolean True if this field allows nulls. False if not.
*/
public static function AllowNull($strTable, $strField) {
$fields=MyActiveRecord::Columns($strTable);
if( isset($fields[$strField]['Null']) ) {
return $fields[$strField]['Null'];
} else {
return false;
}
}
/**
* Escapes a value against a field type in preparation for adding to a sql
* query. Escaping includes wrapping the value in single quotes
*
* @static
* @param mixed mixVal value, eg: true, 1, 'elephant' etc.
* @return mixed escaped value eg: 1, 'o\'reilly' etc.
*/
public static function Escape($mixVal) {
$db =& Database::getInstance();
// clean whitespace
$val = trim( $mixVal );
// magic quotes?
if ( get_magic_quotes_gpc() ) {
$val = stripslashes($val);
}
return("'".$db->escape_string($val)."'");
}
/**
* Given the names of two classes/database tables this method returns
* the name of the table which would link them in a many-to-many
* relationship e.g:
* <code>
* print GetLinkTable('Driver', 'Car') // Car_Driver
* </code>
*
* note that the linking table will order the names of the tables it links
* alphabetically. If you intend to have a many-to-many relationship
* between two classes, you need to create this table in your database.
* The table should have two indexed fields, providing foreign keys to the
* tables they link, e.g. Driver_id, Car_id
*
* NB: This function does NOT check that the table actually exists in the
* database, but presumes that it does.
*
* @static
* @param string strClass1 name of first class/table, e.g. 'Person'
* @param string strClass2 name of second class/table e.g. 'Role'
* @return string name of linking table
*/
public static function GetLinkTable($strClass1, $strClass2) {
$array = array( MyActiveRecord::Class2Table($strClass1), MyActiveRecord::Class2Table($strClass2) );
sort($array);
return implode( '_', $array);
}
/**
* Links two objects together. Presumes the existance of a linking table.
*
* @static
* @param object $obj1 An Object from a subclass of MyActiveRecord
* @param object $obj2 An Object from a subclass of MyActiveRecord
* @return boolean true on success, false on failure
* @see GetLinkTable()
*/
public static function Link(&$obj1, &$obj2) {
$table1=MyActiveRecord::Class2Table($obj1);
$table2=MyActiveRecord::Class2Table($obj2);
$linktable = MyActiveRecord::GetLinkTable($table1, $table2);
$sql = "INSERT INTO {$linktable} ({$table1}_id, {$table2}_id) VALUES ({$obj1->id}, {$obj2->id})";
if( MyActiveRecord::Query($sql) ) {
return true;
} else {
throw new Exception("MyActiveRecord::Link() - Failed to link objects: $table1, $table2"); //E_USER_WARNING
return false;
}
}
/**
* Destroys a link between two objects where it exists
*
* @static
* @param $obj1 An Object from a subclass of MyActiveRecord
* @param $obj2 An Object from a subclass of MyActiveRecord
* @return true on success, false on failure
*/
public static function UnLink(&$obj1, &$obj2) {
$table1=MyActiveRecord::Class2Table($obj1);
$table2=MyActiveRecord::Class2Table($obj2);
$linktable = MyActiveRecord::GetLinkTable($table1, $table2);
$sql = "DELETE FROM {$linktable} WHERE {$table1}_id = {$obj1->id} AND {$table2}_id = {$obj2->id}";
if( MyActiveRecord::Query($sql) ) {
return true;
} else {
throw new Exception("MyActiveRecord::UnLink() - Failed to unlink objects: $table1, $table2"); //E_USER_WARNING
return false;
}
}
/**
* Creates a new object of class strClass. strClass should be
* an extension of MyActiveRecord. arrVals is an optional array of values.
* e.g.:
* <code>
* $person = MyActiveRecord::Create('Person', array( first_name=>'Jake', last_name=>"Grimley' ) );
* </code>
*
* @static
* @param strClass, the name of the subclass.
* @return object of class strClass
*/
function &Create($strClass, $arrVals = null) { //no funciona con static
$obj = new $strClass();
foreach( MyActiveRecord::Columns( $strClass ) as $key=>$field ) {
$obj->$key = $field['Default'];
}
$obj->populate($arrVals);
return $obj;
}
/**
* Counts the number of rows in the database matching the optional
* condition. eg:
* <code>
* print 'There are '.MyActiveRecord::Count('Person').' People in the database.';
* print 'There are '.MyActiveRecord::Count('Person', "last_name LIKE 'Smith'").' People with the surname Smith';
* </code>
*
* @static
* @param string strClass, the name of the class for which you want to create an object.
* @return integer Count. False if the query fails.
*/
function Count( $strClass, $strWhere='1=1' ) { //no funciona con static
$db =& Database::getInstance();
$table = MyActiveRecord::Class2Table($strClass);
$strSQL = "SELECT Count(id) AS count FROM $table WHERE $strWhere";
$rscResult = MyActiveRecord::Query($strSQL);
if( $arr = $db->fetch_array($rscResult) ) {
return $arr['count'];
} else {
return false;
}
}
/**
* Returns an array of objects of class strClass mapped from SQL query
* strSQL. eg:
* <code>
* $people = MyActiveRecord::('Person', 'SELECT * FROM person ORDER BY first_name');
* foreach( $people as $person ) print $person->first_name;
* </code>
*
* @static
* @param string strClass The name of the class for which you want to return objects.
* @param string strSQL The SQL query
* @return array array of objects of class strClass
*/
public static function FindBySql( $strClass, $strSQL, &$foundrows=NULL, $strIndexBy='id') {
$db =& Database::getInstance();
static $cache = array();
$md5 = md5($strSQL);
//echo $strSQL;
if( isset( $cache[$md5] ) && defined('MYACTIVERECORD_CACHE_SQL') && MYACTIVERECORD_CACHE_SQL ) {
return $cache[$md5];
} else {
if( $rscResult = MyActiveRecord::query($strSQL) ) {
$foundrows = $db->found_rows();
//echo $count;
$arrObjects = array();
while( $arrVals = $db->fetch_assoc($rscResult) ) {
//$arrObjects[$arrVals[$strIndexBy]] =& MyActiveRecord::Create($strClass, $arrVals );
$arrObjects[] =& MyActiveRecord::Create($strClass, $arrVals );
//print_r($arrObjects[$arrVals[$strIndexBy]]);
}
//$db =& Database::getInstance();
//$count = $db->found_rows();
//echo $strSQL;
//echo $count;
$db->free_result($rscResult);
return $cache[$md5]=$arrObjects;
} else {
trigger_error("MyActiveRecord::FindBySql() - SQL Query Failed: $strSQL", E_USER_ERROR);
return $cache[$md5]=false;
}
}
}
/**
* Returns an array of all objects of class strClass found in database
* optional where, order and limit paramaters enable the results to be
* narrowed down. eg:
* <code>
* $cars = MyActiveRecord::FindAll('Car');
* $cars = MyActiveRecord::FindAll('Car', "colour='red'", 'make ASC', 10);
* </code>
*
* @static
* @param string strClass the name of the class for which you want objects
* @param mixed mxdWhere optional SQL WHERE fragment, eg: "username='fred' AND password='123'"
* can also be expressed as array, e.g. array( 'username'=>'fred', password=>'123')
* @param string strOrderBy optional SQL ORDER BY fragment, eg: "username ASC"
* @param string intLimit optional integer limiting the number of records returned
* @param string intOffset optional integer to offset the first record brought back
* @return array Array of objects. Array is empty if no ojbects found
*/
public static function FindAll( $strClass, $mxdWhere=NULL, $strOrderBy='id ASC', $intLimit=10000, $intOffset=0, &$foundrows=NULL) {
$table = MyActiveRecord::Class2Table($strClass);
$strSQL = "SELECT SQL_CALC_FOUND_ROWS * FROM $table";
if($mxdWhere) {
$strWhere = ' WHERE ';
if( is_array($mxdWhere) ) {
$conditions = array();
foreach($mxdWhere as $key=>$val) {
$val = addslashes($val);
$conditions[]="$key='$val'";
}
$strWhere.= implode(' AND ', $conditions);
} elseif( is_string($mxdWhere) ) {
$strWhere.= $mxdWhere;
}
$strSQL.=$strWhere;
}
// check for single-table-inheritance
if( strtolower($strClass) != $table )
{
$strSQL.= $mxdWhere ? " AND class LIKE '$strClass' ":" WHERE class LIKE '$strClass' ";
}
$strSQL.=" ORDER BY $strOrderBy LIMIT $intOffset, $intLimit";
$result = MyActiveRecord::FindBySql( $strClass, $strSQL , $foundrows, $strOrderBy);
return $result;
}
/**
* Returns the first object of class strClass found in database
* optional where, order and limit paramaters enable the results to be
* narrowed down
* eg:
* <code>
* $car = MyActiveRecord::FindFirst('Car', "colour='red'", 'model ASC');
* </code>
*
* @static
* @param strClass string, the name of the class for which you want objects
* @param strWhere optional SQL WHERE argument, eg: "username='fred' AND password='123'"
* @param strOrderBy optional SQL ORDER BY argument, eg: "username ASC"
* @return object, false if no objects found
*/
public static function FindFirst( $strClass, $strWhere=NULL, $strOrderBy='id ASC' ) {
$arrObjects = MyActiveRecord::FindAll( $strClass, $strWhere, $strOrderBy, 1 );
if( Count($arrObjects) ) {
return array_shift($arrObjects);
} else {
return false;
}
}
/**
* Returns an object of class strClass found in database with a specific
* integer ID. An array of integers can be passed in order to retrieve an
* array of objects with matching IDs
* eg:
* <code>
* $car = MyActiveRecord::FindById(15);
* $cars = MyActiveRecord::FindById(3, 5, 13);
* </code>
*
* @static
* @param string strClass the name of the class for which you want objects
* @param mixed mxdID integer or array of integers
* @return mixed object, or array of objects
*/
public static function FindById( $strClass, $mxdID ) {
if( is_array($mxdID) ) {
$idlist = implode(', ', $mxdID);
return MyActiveRecord::FindAll( $strClass, "id IN ($idlist)" );
}
else
{
$id = intval($mxdID);
return MyActiveRecord::FindFirst( $strClass, array('id'=>$id) );
}
}
/**
* Static Method to retrieve an array of unique values for a table/column
* along with the total records featuring that unique value
* eg:
* <code>
* foreach( MyActiveRecord::FreqDist('Person', 'first_name') as $name=>$total )
* {
* print "There are $total people with the first name '$name'";
* }
* </code>
*
* @static
* @param string strTable name of database table
* @param string strColumn name of column in table
* @param string strOrder optional sql ORDER fragment (i.e. 'name ASC')
* @param integer limit optional sql LIMIT to number of rows returned
* @return array array with keys containing distinct values and values containing totals
*/
public static function FreqDist($strTable, $strColumn, $strWhere='1=1', $strOrder=null, $intLimit=1000) {
$db =& Database::getInstance();
$table = MyActiveRecord::Class2Table($strTable);
$arr = array();
$strOrder = $strOrder ? $strOrder:$strColumn;
$result = MyActiveRecord::Query("SELECT $strColumn, count(*) AS frequency FROM $table WHERE $strWhere GROUP BY $strColumn ORDER BY $strOrder LIMIT $intLimit");
while( $row = $db->fetch_row($result) ) {
$arr[$row[0]] = $row[1];
}
return $arr;
}
/**
* Static method to insert a new row into the database using class strClass
* and using the values in properties
* eg:
* <code>
* MyActiveRecord::Insert( 'Car', array('make'=>'Citroen', 'model'=>'C4', 'colour'=>'Silver') );
* </code>
*
* @static
* @param string strClass the name of the class/table
* @param array properties array/hash of properties for object/row
* @return boolean true or false depending upon whether insert is successful
*/
function Insert( $strClass, $properties ) {
$object = MyActiveRecord::Create($strClass, $properties);
return $object->save;
}
/**
* Static method to update a row in the database using class strClass
* and using the values in properties
* eg:
* <code>
* MyActiveRecord::Update( 'Car', 1, array('make'=>'Citroen', 'model'=>'C4', 'colour'=>'Silver') );
* </code>
*
* @static
* @param string strClass the name of the class/table
* @param int id the id of the row be updated.
* @param arrray properties array/hash of properties for object/row
* @param boolean true or false depending upon whether update is sucessful
*/
function Update( $strClass, $id, $properties ) {
$object = MyActiveRecord::FindById($strClass, $id);
$object->populate(properties);
return $object->save();
}
/**
* Static method to begin a transaction
* @static
*/
function Begin() {
MyActiveRecord::Query('BEGIN');
return $this;
}
/**
* Static method to roll back a transaction
* @static
*/
function RollBack() {
MyActiveRecord::Query('ROLLBACK');
return $this;
}
/**
* Static method to commit a transaction
* @static
*/
function Commit() {
MyActiveRecord::Query('COMMIT');
return $this;
}
/**
* Saves the object back to the database
* eg:
* <code>
* $car = MyActiveRecord::Create('Car');
* print $car->id; // NULL
* $car->save();
* print $car->id; // 1
* </code>
*
* NB: if the object has registered errors, save() will return false
* without attempting to save the object to the database
*
* @return boolean true on success false on fail
*/
function save() {
$db =& Database::getInstance();
$this->validate();
// if this object has registered errors, we back off and return false.
if( $this->get_errors() ) {
throw new Exception( $this->get_errors());
} else {
$table = MyActiveRecord::Class2Table(get_class($this));
// check for single-table-inheritance
if ( strtolower(get_class($this)) != $table ) {
$this->class = get_class($this);
}
$fields = MyActiveRecord::Columns($table);
// sort out key and value pairs
foreach ( $fields as $key=>$field ) {
if($key!='id') {
$val = MyActiveRecord::Escape( isset($this->$key) ? $this->$key : null );
$vals[]=$val;
$keys[]="`".$key."`";
$set[] = "`$key` = $val";
}
}
// insert or update as required
if( isset($this->id) ) {
$sql="UPDATE `$table` SET ".implode($set, ", ")." WHERE id={$this->id}";
} else {
$sql="INSERT INTO `$table` (".implode($keys, ", ").") VALUES (".implode($vals, ", ").")";
}
$success = MyActiveRecord::Query($sql);
if( !isset($this->id) ) {
$this->id=$db->insert_id();
}
return $this;
}
}
/**
* Sets all object properties via an array
*
* @param array $arrVals array of named values
* eg:
* <code>
* $car->populate( array('make'=>'Citroen', 'model'=>'C4', 'colour'=>'red') );
* $car->populate( $_POST );
* </code>
*
* @param array $arrVals
* @return boolean true if $arrVals is valid array, false if not
*/
function populate($arrVals) {
//TODO maybe should be moved to ActiveResource
if( is_array($arrVals) ) {
foreach($arrVals as $key=>$val) {
$this->$key=$val;
}
return $this;
} else {
//throw new Exception('Not an array.');
//TODO normalmente null pero puede ser otra cosa
return $this;
}
}
/**
* Deletes the object from the database
* eg:
* <code>
* $car = MyActiveRecord::FindById('Car', 1);
* $car->destroy();
* </code>
*
* @return boolean True on success, False on failure
*/
function destroy() {
$table = MyActiveRecord::Class2Table($this);
MyActiveRecord::Query( "DELETE FROM $table WHERE id ={$this->id}" );
return $this;
}
/**
* alias of destroy()
* @see destroy()
*/
function delete() {
return $this->destroy();
}
/*
* Adds a child object of class strClass to this object
* eg:
* <code>
* $driver = MyActiveRecord::FindById('Driver', 1);
* $car = $driver->add_child('Car', array('make'=>'citroen', model'=>'c4') );
* $car->save();
* </code>
* @param string strClass class of object we wish to add
* @param properties array optional array of properties for new object
* @return object object of class 'strClass'
*/
function add_child($strClass, $properties=null) {
$object = MyActiveRecord::Create($strClass, $properties);
$key = MyActiveRecord::Class2Table($this)."_id";
$object->$key = $this->id;
return $object;
}
/**
* Attaches another object to the object
* NB: You must have saved the object you want to attach before attaching
* it eg:
* <code>
* $post = MyActiveRecord::Create('Post');
* $post->populate( 'title'=>'New Post' );
* $post->save();
* $topic->attach('post');
* </code>
*
* @param object $obj the object you wish to attach
* @return boolean True on success. False on failure.
*/
function attach(&$obj) {
if( $this->id && $obj->id ) {
return MyActiveRecord::Link($this, $obj);
} else {
throw new Exception('MyActiveRecord::attach() - both objects must be saved before you can attach');
//return false;
}
}
/**
* Detaches an object from the object
* eg:
* <code>
* // detach old posts
* foreach( $topic->find_attached('Post') as $post )
* {
* if( $post->created < mktime()-5000000 )
* {
* $topic->detach($post);
* }
* }
* </code>
*
* @param object $obj object to be detached
*/
function detach(&$obj) {
return MyActiveRecord::UnLink($this, $obj);
}
/**
* Sets all attached links via an array of IDs
* e.g.
* <code>
* $topic->set_attached('Post', array(1, 8, 32) );
* $topic->set_attached('Post', $_POST['id_list']);
* </code>
* NB: set_attached will destroy any existing attachments for the class strClass
* BEFORE creating new attachments
*
* @param string strClass class of objects to be set as attached
* @param array arrID array of object IDs
* @return boolean True on success. False on failure.
*/
function set_attached($strClass, $arrID) {
if( is_array($arrID) ) {
if (count($arrID) == 0)
return true; //fixed, empty array
MyActiveRecord::Begin();
$pass = true;
foreach( $this->find_linked($strClass) as $fObject ) {
$this->detach($fObject) or $pass=false;
}
foreach( MyActiveRecord::FindById($strClass, $arrID) as $fObject ) {
$this->attach($fObject) or $pass=false;
}
$pass ? MyActiveRecord::Commit() : MyActiveRecord::RollBack();
return $pass;
} else {
throw new Exception('MyActiveRecord::set_attached() - Second argument not an array'); // E_USER_NOTICE
return false;
}
}
/**
* Sets the date of the property specified by strKey
* @param string strKey property to be set
* @param int intTimeStamp unix timestamp
*/
function set_date($strKey, $intTimeStamp=null) {
$this->$strKey = MyActiveRecord::DbDate($intTimeStamp);
}
/**
* Sets the datetime of the property specified by strKey
* @param string strKey property to be set
* @param int intTimeStamp unix timestamp
*/
function set_datetime($strKey, $intTimeStamp=null) {
$this->$strKey = MyActiveRecord::DbDateTime($intTimeStamp);
}
/**
* Retrieves a date or datetime fields as a unix timestamp
* @param string strKey property to be retrieved
*/
function get_timestamp($strKey) {
return MyActiveRecord::TimeStamp($this->$strKey);
}
/**
* returns 'parent' object.
* e.g.
* <code>
* $topic = $post->find_parent('Topic');
* </code>
*
* In order for the above to work, you would need to have an integer
* field called 'Topic_id' in your 'Post' table. MyActiveRecord will take
* care of the rest.
*
* @param string strClass Name of the class of objects to return in the array
* @param string strForeignKey Optional specification of foreign key at runtime
* @return object object of class strClass
*/
function find_parent($strClass, $strForeignKey=NULL) {
$key = $strForeignKey or $key=strtolower( $strClass.'_id' );
return MyActiveRecord::FindById($strClass, $this->$key);
}
/**
* returns array of 'child' objects.
* e.g.
* <code>
* foreach( $topic->find_children('Post') as $post ) print $post->subject;
* </code>
*
* In order for the above to work, you would need to have an integer field called 'Topic_id'
* in your 'Post' table. MyActiveRecord will take care of the rest.
*
* @param string strClass Name of the class of objects to return in the array
* @param mixed mxdCondition Either a SQL 'WHERE' fragment or an array of paramaters that must be matched ( see FindAll() )
* @param string strOrderBy a SQL ORDER BY strring fragment
* @param integer intLimit limit on number of records to retrieve
* @param integer intOffset if you don't want to begin with the first child you can add an offset here
* @param strForeignKey if the foreign key is not parent_id but something different you can specify here
* @param mixed optional sql condition expressed as either a sql string or an array
* eg: 'flagged=true' or array( 'flagged'=>1 );
* @return array array containing objects of class strClass
*/
function find_children($strClass, $mxdCondition=NULL, $strOrderBy='id ASC', $intLimit=10000, $intOffset=0, $strForeignKey=NULL) {
// name of foreign key:
$key = $strForeignKey ? $strForeignKey : strtolower( get_class($this).'_id' );
if ( is_array($mxdCondition) || is_null($mxdCondition) ) {
// specifiy condition as an array
$mxdCondition[$key]=$this->id;
return MyActiveRecord::FindAll( $strClass, $mxdCondition, $strOrderBy, $intLimit, $intOffset );
} else {
// condition is non-null string
$fullSQLCondition = "$key=$this->id AND ($mxdCondition)";
return MyActiveRecord::FindAll( $strClass, $fullSQLCondition, $strOrderBy, $intLimit, $intOffset );
}
}
/**
* returns array of 'linked' objects. (many-to-many relationship)
* e.g.
* <code>
* foreach( $user->find_linked('Role') as $role ) print $role->name;
* </code>
*
* In order for the above to work, you would need to have a linking table
* called Role_User in your database, containing the fields role_id and user_id
*
* @param string strClass Name of the class of objects to return in the array
* @param string strCondition Optional SQL condition, e.g. 'password NOT NULL'
* @return array array containing objects of class strClass
*
*/
function find_linked($strClass, $mxdCondition=null, $strOrder=null) {
if($this->id) {
// only attempt to find links if this object has an id
$table = MyActiveRecord::Class2Table($strClass);
$thistable = MyActiveRecord::Class2Table($this);
$linktable=MyActiveRecord::GetLinkTable($table, $thistable);
$strOrder = $strOrder ? $strOrder: "{$strClass}.id";
$sql= "SELECT {$table}.* FROM {$table} INNER JOIN {$linktable} ON {$table}_id = {$table}.id WHERE $linktable.{$thistable}_id = {$this->id} ORDER BY $strOrder";
if( is_array($mxdCondition) ) {
foreach($mxdCondition as $key=>$val) {
$val = addslashes($val);
$sql.=" AND $key = '$val' ";
}
} else {
if($mxdCondition) $sql.=" AND $mxdCondition";
}
return MyActiveRecord::FindBySql($strClass, $sql);
} else {
return array();
}
}
/**
* Alias of find_linked()
* @link find_linked()
*/
function find_attached($strClass, $strCondition=NULL) {