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 = Dog.id as a FK relationship.
- require_once ‘Crtx/DB/DataObject.php‘;
- class Dog extends Crtx_DB_DataObject { }
- class Flea extends Crtx_DB_DataObject { }
- $dog = new Dog($dsn);
- $dog_record = $dog->find(42);
- // has_many relationship, 1:*
- $fleas = $dog_record->fleas() // Returns an array of fleas that have a Fleas.dog_id equal to $dog_record->id
- $flea = new Flea($dsn);
- $flea_record = $flea->find(457);
- // belongs_to relationship, 1:1
- $dog = $flea_record->dog(); // Returns a single Record object for the related Dog, that is, where Dogs.id = $flea->Dog_id
Note the singular and plural of the dog() and
Truncated by Planet PHP, read more at the original (another 531 bytes)