forked from maintainable/framework
/
Base.php
3473 lines (3134 loc) · 106 KB
/
Base.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
/**
* @category Mad
* @package Mad_Model
* @copyright (c) 2007-2009 Maintainable Software, LLC
* @license http://opensource.org/licenses/bsd-license.php BSD
*/
/**
* Object Relation Mapper (ORM) Layer. Tables are represented as classes, rows in
* the table correspond to objects from that class, and columns map to the object
* attributes. Handles all basic CRUD operations (Create, Read, Update, Delete).
*
* Model subclasses should always be created with the generator to ensure creation of
* all correct components (including data objects, unit tests, and fixtures):
*
* <code>
* php ./script/generate.php model {ModelName} {table_name}
* </code>
*
* @category Mad
* @package Mad_Model
* @copyright (c) 2007-2009 Maintainable Software, LLC
* @license http://opensource.org/licenses/bsd-license.php BSD
*/
abstract class Mad_Model_Base extends Mad_Support_Object
{
/*##########################################################################
# Configuration options
##########################################################################*/
/**
* Should the table introspection data be cached
* - true: Cache table introspection data to /tmp/cache/tables
* - false: Introspect database table on every request
*/
public static $cacheTables = true;
/**
* Include the root level in json serialization
*/
public static $includeRootInJson = false;
/*##########################################################################
# Connection
##########################################################################*/
/**
* @var object
*/
protected static $_connectionSpec;
/**
* @var array
*/
protected static $_activeConnection;
/**
* @var Logger
*/
protected static $_logger;
/**
* Database adapter instance
* @var Mad_Model_ConnectionAdapter_Abstract
*/
public $connection;
/*##########################################################################
# Attributes
##########################################################################*/
/**
* List of attributes excluded from mass assignment
* @var array
*/
protected $_attrProtected = array();
/**
* List of attribute name=>value pairs
* @var array
*/
protected $_attributes = array();
/**
* Name of this class
* @var string
*/
protected $_className = null;
/**
* Name of the database table
* @var string
*/
protected $_tableName = null;
/**
* Name of the primary key db column
* @var string
*/
protected $_primaryKey = null;
/**
* Has subclasses through a types table with class_name column
* @var boolean
*/
protected $_inheritanceColumn = 'type';
/**
* @var array
*/
protected $_columns = array();
/**
* @var array
*/
protected $_columnsHash = array();
/**
* @var array
*/
protected $_columnNames = array();
/**
* An object cannot allow attribute access once it has been destroyed
* @var boolean
*/
protected $_frozen = false;
/**
* Is this a new record to be inserted?
* @var boolean
*/
protected $_newRecord = true;
/*##########################################################################
# Associations
##########################################################################*/
/**
* Has the association changed (even though the actual model might not have)
* @var boolean
*/
protected $_assocChanged = false;
/**
* A list of associations for this model define in concrete _initialize()
* Lazy initialized if an unknown property/method is called
*
* @var array
*/
protected $_associationList;
/**
* The list of association objects for this model
* Lazy initialized if an unknown property/method is called
*
* @var array
*/
protected $_associations;
/**
* The list of methods that are available for the associations of this model
* $_associationMethods['createDocument'] = $hasOneAssociationObject;
* This is lazy initialized if an unknown propery/method is called
*
* @var array
*/
protected $_associationMethods;
/*##########################################################################
# Validations
##########################################################################*/
/**
* The list of validations that thie model enforces before an update/insert
* @var array
*/
protected $_validations = array();
/**
* Should we throw exceptions when validations fail
* @var array
*/
protected $_throw = false;
/**
* An array of messages stored when validations fail
* @var array
*/
public $errors;
/*##########################################################################
# Construct/Destruct
##########################################################################*/
/**
* Initialize any values given for the model.
*
* Load the model by attributes
* <code>
* <?php
* ...
* $attributes = array('documentname' => 'My Folder',
* 'description' => 'My Description');
* $folder = new Folder($attributes);
* ...
* ?>
* </code>
*
* @param array $attributes construct by attribute list
* @param array $options 'include' associations
* @throws Mad_Model_Exception
*/
public function __construct($attributes=null, $options=null)
{
$this->_className = get_class($this);
// establish connection to db
$this->connection = $this->retrieveConnection();
$this->errors = new Mad_Model_Errors($this);
// Initialize relationships/data-validation from subclass
$this->_initialize();
// init table/fields
$this->_tableName = $this->tableName();
$this->_primaryKey = $this->primaryKey();
$this->_attributes = $this->_attributesFromColumnDefinition();
// set values by attribute list
if (isset($attributes)) {
$this->setAttributes($attributes);
}
}
/**
* Clone the object without the values. All objects need to be explicitly
* copied or we get them referencing the same data
*/
public function __clone()
{
// reset attributes, errors, and associations
$this->_attributes = $this->_attributesFromColumnDefinition();
$this->errors->clear();
$this->_resetAssociations();
// only need to clone validations if they exist
if (isset($this->_validations)) {
foreach ($this->_validations as &$validation) {
$validation = clone $validation;
}
}
}
/**
* Initialize relationships and Data validation from subclass
*/
abstract protected function _initialize();
/*##########################################################################
# Magic Accessor methods
##########################################################################*/
/**
* Dynamically get value for a attribute. Attributes cannot be retrieved once
* an object has been destroyed.
*
* @param string $name
* @return string
* @throws Mad_Model_Exception
*/
public function _get($name)
{
// active-record primary key value
if ($name == 'id') { $name = $this->primaryKey(); }
// active-record || attribute-reader value
if (array_key_exists($name, $this->_attributes)) {
return $this->readAttribute($name);
}
// dynamic attribute added by an association
$this->_initAssociations();
if (isset($this->_associationMethods[$name])) {
return $this->_associationMethods[$name]
->callMethod($name, array());
// unknown attribute
} else {
throw new Mad_Model_Exception("Unrecognized attribute '$name'");
}
}
/**
* Dynamically set value for a attribute. Attributes cannot be set once an
* object has been destroyed. Primary Key cannot be changed if the data was
* loaded from a database row
*
* @param string $name
* @param mixed $value
* @throws Mad_Model_Exception
*/
public function _set($name, $value)
{
if ($this->_frozen) {
$msg = "You cannot set attributes of a destroyed object";
throw new Mad_Model_Exception($msg);
}
// active-record primary key value
if ($name == 'id') { $name = $this->primaryKey(); }
// cannot change pk if it's already set
if (($name == $this->primaryKey()) && !$this->isNewRecord()) {
// ignore assignment of pk so that this works with activeresource
return;
}
// active-record || attribute-reader value
if (array_key_exists($name, $this->_attributes)) {
return $this->writeAttribute($name, $value);
}
// dynamic attribute added by an association
$this->_initAssociations();
if (isset($this->_associationMethods[$name.'='])) {
return $this->_associationMethods[$name.'=']
->callMethod($name.'=', array($value));
// unknown attribute
} else {
throw new Mad_Model_Exception("Unrecognized attribute '$name'");
}
}
/**
* Allows testing with empty() and isset() to work inside templates
*
* @param string $key
* @return boolean
*/
public function _isset($name)
{
// association methods
$this->_initAssociations();
if (isset($this->_associationMethods[$name])) {
return count($this->_get($name)) > 0;
// active-record attribue
} else {
return isset($this->_attributes[$name]);
}
return isset($this->_attributes[$name]);
}
/**
* Association methods are added at runtime and use dynamic methods.
*
* @param string $name
* @param array $args
*/
public function __call($name, $args)
{
// dynamic attribute added by an association
$this->_initAssociations();
if (isset($this->_associationMethods[$name])) {
return $this->_associationMethods[$name]->callMethod($name, $args);
// unknown method
} else {
throw new Mad_Model_Exception("Unrecognized method '$name'");
}
}
/**
* Print out a string describing this object's attributes
*
* @return string
*/
public function __toString()
{
foreach ($this->_attributes as $name => $value) {
$str[] = "$name => ".(isset($value) ? "'$value'" : 'null');
}
return isset($str) ? "\n".$this->_className." Object: \n".join(", \n", $str) : null;
}
/*##########################################################################
# Serialization
##########################################################################*/
/**
* Serialize only needs attributes
*/
public function __sleep()
{
return array('_attributes', '_attrReaders',
'_attrWriters', '_attrValues');
}
/**
* Enables models to be used as URL parameters for routes automatically.
*
* @return null|string
*/
public function toParam()
{
$pk = $this->primaryKey();
if ($pk && isset($this->_attributes[$pk])) {
return (string)$this->_attributes[$pk];
}
}
/*##########################################################################
# Logger
##########################################################################*/
/**
* Set a logger object, defaulting to mad_default_logger. This needs to
* reset connection so that the correct log is passed to the connection
* adapter.
*
* @param object $logger
*/
public static function setLogger($logger=null)
{
self::$_logger = isset($logger) ? $logger : $GLOBALS['MAD_DEFAULT_LOGGER'];
self::establishConnection(self::removeConnection());
}
/**
* Returns the logger object.
*
* @return object
*/
public static function logger()
{
// set default logger
if (!isset(self::$_logger)) {
self::setLogger();
}
return self::$_logger;
}
/*##########################################################################
# Connection Management
##########################################################################*/
/**
* Establishes the connection to the database. Accepts a hash as input where
* the :adapter key must be specified with the name of a database adapter (in lower-case)
*
* Example for regular databases (MySQL, Postgresql, etc):
* <code>
* Mad_Model_Base::establishConnection(array(
* "adapter" => "mysql",
* "host" => "localhost",
* "username" => "myuser",
* "password" => "mypass",
* "database" => "somedatabase"
* ));
* </code>
*
* Example for SQLite database:
* <code>
* Mad_Model_Base::establishConnection(array(
* "adapter" => "sqlite",
* "database" => "path/to/dbfile"
* ));
* </code>
*
* The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
* may be returned on an error.
*
* @param array $spec
* @return Connection
*/
public static function establishConnection($spec=null)
{
// $spec is empty: $spec defaults to MAD_ENV string like "development"
// keep going to read YAML for this environment string
if (empty($spec)) {
if ( !defined('MAD_ENV') || !MAD_ENV ) {
throw new Mad_Model_Exception('Adapter Not Specified');
}
$spec = MAD_ENV;
}
// $spec is string: read YAML config for environment named by string
// keep going to process the resulting array
if (is_string($spec)) {
$config = Horde_Yaml::loadFile(MAD_ROOT.'/config/database.yml');
$spec = $config[$spec];
}
// $spec is an associative array
if (is_array($spec)) {
// validation of array is handled by horde_db
self::$_connectionSpec = $spec;
} else {
throw new Mad_Model_Exception("Invalid Connection Specification");
}
}
/**
* Returns true if a connection that's accessible to this class have already
* been opened.
*
* @return boolean
*/
public static function isConnected()
{
return isset(self::$_activeConnection);
}
/**
* Locate/Activate the connection
*
* @return Mad_Model_ConnectionAdapter_Abstract
*/
public static function retrieveConnection()
{
// already have active connection
if (self::$_activeConnection) {
$conn = self::$_activeConnection;
// connection based on spec
} elseif ($spec = self::$_connectionSpec) {
if (empty($spec['logger'])) {
$spec['logger'] = self::logger();
}
$adapter = Horde_Db_Adapter::getInstance($spec);
$conn = self::$_activeConnection = $adapter;
}
if (empty($conn)) {
throw new Mad_Model_Exception("Connection Not Established");
}
return $conn;
}
/**
* Remove the connection for this class. This will close the active
* connection and the defined connection (if they exist). The result
* can be used as argument for establishConnection, for easy
*/
public static function removeConnection()
{
$spec = self::$_connectionSpec;
$conn = self::$_activeConnection;
self::$_connectionSpec = null;
self::$_activeConnection = null;
if ($conn) { $conn->disconnect(); }
return $spec ? $spec : '';
}
/**
* Returns the connection currently associated with the class. This can
* also be used to "borrow" the connection to do database work unrelated
* to any of the specific Active Records.
*
* @return Mad_Model_ConnectionAdapter_Abstract
*/
public static function connection()
{
if (self::$_activeConnection) {
return self::$_activeConnection;
} else {
return self::$_activeConnection = self::retrieveConnection();
}
}
/*##########################################################################
# DB Table column/keys
##########################################################################*/
/**
* Get the name of the table
* @return string
*/
public function tableName()
{
if (isset($this->_tableName)) {
return $this->_tableName;
} else {
return $this->resetTableName();
}
}
/**
* Reset the table name based on conventions
*
*/
public function resetTableName()
{
return $this->_tableName =
Mad_Support_Inflector::tableize($this->baseClass());
}
/**
* Get the name of the primary key column
* @return string
*/
public function primaryKey()
{
if (isset($this->_primaryKey)) {
return $this->_primaryKey;
} else {
return $this->resetPrimaryKey();
}
}
/**
* Rest primary key name based on conventions.
*/
public function resetPrimaryKey()
{
return $this->_primaryKey = 'id';
}
/**
* Get class name column used for single-table inheritance
*
* @return string
*/
public function inheritanceColumn()
{
return $this->_inheritanceColumn;
}
/**
* Set the name of the table for the model
* @param string $table
*/
public function setTableName($value)
{
$this->_tableName = $value;
}
/**
* Set the name of the table for the model
* @param string $value
*/
public function setPrimaryKey($value)
{
$this->_primaryKey = $value;
}
/**
* Change the default column used for single-table inheritance
* @param string $col
*/
public function setInheritanceColumn($col)
{
$this->_inheritanceColumn = $col;
}
/**
* Returns an array of column objects for the table associated
* with this class.
*
* @return array
*/
public function columns()
{
if (empty($this->_columns)) {
$this->_columns = $this->connection->columns($this->tableName(),
"$this->_className Columns");
foreach ($this->_columns as $col) {
$col->setPrimary($col->getName() == $this->_primaryKey);
}
}
return $this->_columns;
}
/**
* Returns a hash of column objects for the table associated with
* this class.
*
* @return array
*/
public function columnsHash()
{
if (empty($this->_columnsHash)) {
foreach ($this->columns() as $col) {
$this->_columnsHash[$col->getName()] = $col;
}
}
return $this->_columnsHash;
}
/**
* Returns an array of column names as strings.
*
* @return array
*/
public function columnNames()
{
if (empty($this->_columnNames)) {
foreach ($this->columns() as $col) {
$this->_columnNames[] = $col->getName();
}
}
return $this->_columnNames;
}
/**
* Reset the column info
*/
public function resetColumnInformation()
{
$this->_columns = $this->_columnsHash =
$this->_columnNames = $this->_inheritanceColumn = null;
}
/**
* Get the base class for this model. Defined by subclass
*
* @return string
*/
public function baseClass()
{
// go up single hierarchy if this is an STI model
$parentClass = get_parent_class($this);
if ($parentClass != 'Mad_Model_Base') {
return $parentClass;
}
return $this->_className;
}
/*##########################################################################
# Attributes
##########################################################################*/
/**
* Set list of attributes protected from mass assignment
*
* @todo implement this in save statements
* @param string $attribute
*/
public function attrProtected($attributes)
{
$names = func_get_args();
$this->_attrProtected = array_unique(
array_merge($this->_attrProtected, $names));
}
/**
* Get the value for an attribute in this model
*
* @param string $name
* @return string
*/
public function readAttribute($name)
{
// active-record attributes
if (array_key_exists($name, $this->_attributes)) {
return $this->_attributes[$name];
// no value set yet
} else {
return null;
}
}
/**
* Set the value for an attribute in this model
*
* @param string $name
* @param mixed $value
*/
public function writeAttribute($name, $value)
{
// active-record attributes
if (array_key_exists($name, $this->_attributes)) {
$this->_attributes[$name] = $value;
}
}
/**
* Get the human attribute name for a given attribute
*
* @return string
*/
public function humanAttributeName($attr)
{
$col = $this->columnForAttribute($attr);
return Mad_Support_Inflector::humanize($col->getName());
}
/**
* Get the array of attribute fields
* @return array
*/
public function getAttributes()
{
return $this->_attributes;
}
/**
* Mass assign attributes for this model
* @param array $attributes
*/
public function setAttributes($attributes = array())
{
// Set attributes by array
if (is_array($attributes)) {
foreach ($attributes as $attribute => $value) {
$this->$attribute = $value;
}
// Set primary key (Beware this does not instantiate other properties)
} elseif (is_numeric($attributes)) {
$this->{$this->primaryKey()} = $attributes;
}
}
/**
* Finder methods must instantiate through this method to work with the
* single-table inheritance model that makes it possible to create
* objects of different types from the same table.
*
* @param array $record
*/
public function instantiate($record)
{
// single table inheritance
$column = $this->inheritanceColumn();
if (isset($record[$column]) && $className = $record[$column]) {
if (!class_exists($className)) {
$msg = "The single-table inheritance mechanism failed to ".
"locate the subclass: '$className'. This error is raised ".
"because the column '$column' is reserved for storing the ".
"class in case of inheritance. Please rename this column ".
"if you didn't intend it to be used for storing the ".
"inheritance class.";
throw new Mad_Model_Exception($msg);
}
$model = new $className;
} else {
$model = clone $this;
}
return $model->setValuesByRow($record);
}
/**
* Set the values for this object using a db result set.
*
* <code>
* <?php
* ...
* $folder = new Folder();
* $row = $result->fetchRow();
* $folder->setValuesByRow($row)
* ...
* ?>
* </code>
*
* @param array $dbValues
* @return Mad_Model_Base
*/
public function setValuesByRow($values)
{
// active-record attributes
foreach ($this->_attributes as $name => $value) {
if (array_key_exists($name, $values)) {
$this->writeAttribute($name, $values[$name]);
}
}
// attr-writers
foreach ($this->_attrWriters as $name) {
if (array_key_exists($name, $values)) {
$this->$name = $values[$name];
}
}
// this isn't a new record if we've loaded it from the db
$this->_newRecord = false;
return $this;
}
/**
* Returns an array of names for the attributes available on this
* object sorted alphabetically.
*
* @return array
*/
public function attributeNames()
{
$attrs = array_keys($this->_attributes);
sort($attrs);
return $attrs;
}
/**
* Returns the column object for the named attribute
*
* @param string $name
* @return object
*/
public function columnForAttribute($name)
{
$colHash = $this->columnsHash();
return $colHash[$name];
}
/*##########################################################################
# Deprecated column accessors
##########################################################################*/
/**
* Get an array of columns
* @deprecated
* @param string $tblAlias prepend table alias to columns
* @param boolean $colAlias Generate column aliases for TO_CHAR()s
* @return array
*/
public function getColumns($tblAlias=null, $colAlias=true)
{
$tblAlias = isset($tblAlias) ? "$tblAlias." : null;
foreach ($this->_attributes as $name => $value) {
$cols[] = $tblAlias.($name);
}
return isset($cols) ? $cols : array();
}
/**
* Construct the column string from the columns. Convert timestamps to string (TO_CHAR)
* @deprecated
* @param string $tblAlias prepend table alias to columns
* @param boolean $colAlias Generate column aliases for TO_CHAR()s
* @return string
*/
public function getColumnStr($tblAlias=null, $colAlias=true)
{
foreach ($this->getColumns($tblAlias, $colAlias) as $col) {
$parts = explode('.', $col);
// has table alias
if (isset($parts[1])) {
$quoted[] = $this->connection->quoteColumnName($parts[0]).'.'.
$this->connection->quoteColumnName($parts[1]);
// column only
} else {
$quoted[] = $this->connection->quoteColumnName($parts[0]);
}
}
return join(', ', $quoted);
}
/**
* Get the insert values string from the columns.
* @deprecated
* @return string
*/
public function getInsertValuesStr()
{
$vals = array();
foreach ($this->_attributes as $name => $value) {
$vals[] = $this->_quoteValue($value);
}
return join(', ', $vals);
}
/*##########################################################################
# Associations
##########################################################################*/
/**
* Returns the Association object for the named association
*
* @param string $name
* @return Mad_Model_Association_Base
*/
public function reflectOnAssociation($name)
{
$this->_initAssociations();
if (! isset($this->_associations[$name])) {
throw new Mad_Model_Exception("Association $name does not exist for ".get_class($this));
}