Search code examples
phpormoopphp4

Best practices / info: Writing a PHP4 ORM


For a number of reasons (all of which can, basically, be broken down to bad management decisions) we're unable to switch to PHP5, meaning we'll have to support PHP4 for probably a few more years.

Since a lot of our applications (as with a lot of web apps) are glorified CRUD apps, and because I like to pick up the occasional home project to waste some time on, I'm currently writing a small ORM-like class that will serve as a wrapper for most basic queries (insert, update, replace, delete, among others.) Since it has to support PHP4, PDO is out of the question, so I'll have to fall back to language-specific functions such as mysql_query. Because we're using a few different systems, in a variery of versions (Interbase versions 4 and above, Firebird, MySQL), my ORM / Wrapper class (not sure what to call it), is bound to grow big.

To tackle this problem, I've thought of two possible 'solutions':

  • Write one massive class, with switch statements inside the functions based on a $database_system variable that defines the language/RDBMS used
  • Write one base class, and write one derived class per RDBMS (possibly per version, if the features differ a lot between them).

Currently I'm leaning towards the second option; in my view, it makes maintenance easier, especially when adding a new RDBMS to the supported list. On the other hand, with every RDBMS using it's own set of PHP functions, I'm not sure how much there would be to inherit from a base class. Keeping in mind this class will eventually support features such as queuing, executing (and possibly committing, if supported) a whole list of queries at once.

Given this situation, which approach would be best? A or B, or is there possibly a C which I didn't consider yet? Some examples of existing classes would be perfect, unfortunately most ORM's I've come across rely on the (PHP5 only) PDO class.


Solution

  • Definitely go with your option 2. Your OO approach is superior to the massive switch statement. Your base class will give you more than just inheriting common methods. It gives you a consistent interface which can later be used as an adapter when you migrate to some other database persistence strategy (PHP5/PDO when management comes to their senses?). I would even closely model your interface after PDO to the point where PDO could even be a drop-in replacement for your homegrown persistence layer if needed. Additionally, the learning curve for new developers on the project learning your persistence layer will be lower if they already have experience with PDO.