Like a Train going down hill….

I have made some enhancements to Crtx_DB_DataObject this last week, one of which I really like.

One of the great things about ActiveRecord? is its handling of Relationships.

ActiveRecord? has this ability to specify that a record from a specific table belongs_to or that it is related to a number of other records in another table has_many. Furthermore, it supports lookup tables using has_and_belongs_to_many.

There are two things I don’t like about the way ActiveRecord? handles these relationships; First you must explicitly specify these relationships in the classes for these records (or rather, for the table) and secondly, the related records are loaded automatically.

Crtx_DB_DataObject gleans it knowledge of relationships from the columns in a record, and can therefore resolve these relationships automatically. An example is this:

Assuming a scheme where we have one Dog in a table called Dogs which is related to many Fleas in a table called Fleas using Fleas.Dog_id = as a FK relationship.

  2.  require_once Crtx/DB/DataObject.php;
  4.  class Dog extends Crtx_DB_DataObject { }
  6.  class Flea extends Crtx_DB_DataObject { }
  8.  $dog = new Dog($dsn);
  10.  $dog_record  = $dog->find(42);
  12.  // has_many relationship, 1:*
  13.  $fleas = $dog_record->fleas() // Returns an array of fleas that have a Fleas.dog_id equal to $dog_record->id
  15.  $flea = new Flea($dsn);
  17.  $flea_record = $flea->find(457);
  19.  // belongs_to relationship, 1:1
  20.  $dog = $flea_record->dog(); // Returns a single Record object for the related Dog, that is, where = $flea->Dog_id
  21.  ?>

Note the singular and plural of the dog() and

Truncated by Planet PHP, read more at the original (another 531 bytes)