1: I personally wouldn’t advocate building your own ORM unless
a) it’s for academic interest
b) you’re a sucker for punishment
c) you have a genuine new twist on the ORM concept
2: As far as real world examples are concerned, I’d check out Redbean or Doctrine 2 (when it’s launched). The former is built more along the Active Record lines, the latter seems to have more Data Mapper functionality.
Active Record is just simpler to implement - since the object itself takes care of database interaction - and tends to look something like this:
$User = new User(1);//denotes id in user table
$User->changeVariable($value);
$User->save;
Ideally there should be some mechanism to avoid this problem
$User = new User(1);
$User2 = new User(1); //same record, different object
$User->changeVariable($up);
$User2->changeVariable($down);
$User->save();
$User1->save();// uh oh - you just wrote a new value by accident
So you might have something like this instead to mitigate the problem. In this example, the Active Record class maintains an internal array of instantiated classes.
$User = ActiveRecord::load('user',1);
$User = ActiveRecord::load('user',2);//same object, different reference variable
$User->changeVariable($up);
$User2->changeVariable($down);
$User->save();//this will save $down
$User1->save();// no change
You would never see the users instantiated next to each other like this, but if you load the user in one part of the script, and it gets loaded again elsewhere - you can get this kind of problem.
That doesn’t even demonstrate memory management mechanisms to prevent thousands of records being hydrated into classes by default…
DAO means Data Access Object -I fell into my own trap, it’s a generic term for an object within the DBAL, Database Abstraction Layer. What I meant to say is wrap up your statements in a transaction script, and try and group them by purpose.
I often just use an abstract DAO class to contain my most common transactions (a typical Transaction Script):
select,
selectID,
selectWhere,
selectFilter //allows for more complex queries
insert,
update,
delete.
The main purpose of the class is to automate sql generation and quote values. Subsequent DAO classes can extend that, and add custom SQL where required. Not very pure - but pretty simple way to organise the project.
An alternative route would be to make a fluent interface class instead, with functions like select(), where(), order() so that you could dynamically build a statement using those methods instead. Zend_DB uses something like this (as well as offering Table Gateways, Row Gateways - just Google these names, they’re simple patterns to understand.)
Ultimately, you’re not honour bound to use ORM if you don’t want to, and in some cases it’s just a hindrance. Mappers, Transactions, Active Records, whatever, just pick what works for your project.