CakePHP and Persistence, Part 1: Why not Objects?

May 17th, 2007

Cake is a decent framework. In fact I have very little gripes about it all around - plently of little picky things, but only one that really bugs me: cake’s model implementation.

Cake’s finders inherited by all models (find, findAll, etc) return 3d hashes, keyed at the top by the model class name, the middle with field names (model properties), and the bottom with the field values. This is a nice simple way of handling things, and does indeed work well for smaller applications. I’ve worked on several that attest to its usefulness (http://rosaloves.com for one).

Now for the rant: This Does Not Scale. Because we must deal in arrays instead of objects, we lose two very important OOP abilities - encapsulation and polymorphism. Our result models are not objects, so they are incapable of such notions. We have no typing, no method signatures, and therefore no effective interface. All entities must then have intimate knowledge of how our model is composed. There’s no point in getting into why this is bad - it has been documented over and over since the inception of OOP.

Why arrays? I am not involved in Cake’s development (though I hope to be an accepted contributor soon), so I can’t speak for them. In comparison with Ruby on Rails, I will wager a guess. Firstly, Rails’ finders are basically static methods (static as in Java), called class methods in Ruby, if I’m not mistaken. These methods only exist once in memory, as opposed to instance methods, which exsist per object instance. Static/class methods cannot operate on instance data (at least in Java, where ‘this’ is invalid). I’d wager that Rails’ finders/savers, as well as all relational mapping metadata, are static class members. This way model instances don’t carry (duplicate) this data per instance.
Php 4 can’t do this, not cleanly or naturally anyway, so Cake uses model instances singularly, probably to emulate the feel of executing finds in Rails. If Cake returned model instances (which it should), each instance would carry copies of the relational mapping data. If Cake exploited php 5, this metadata could be static and therefore shared between all instances of the model class. This could be achieved in a few ways in php 4, but it would be messy to say the least.

I’m only guessing that this is one of the reasons Cake does what it does. I’ll continue with a later post going further on thsi topic, as well as get into a project I’ve started on CakeForge called Object Model (http://cakeforge.org/projects/object-model/).

Fresh Blog.

June 19th, 2006

Blog is back, this time with a proper look. All the old content has been dumped, mainly because it was useless fluff to satisfy my experiment with wordpress.