OOP in 09
As a web developer I’m constantly looking for ways to improve my techniques, and one big change I made this year worked out better than expected. For the two large sites I built from the ground up this year (and a third, smaller site), I used Object Oriented Programming (OOP) for the first time.
I’d tried wrapping my mind around OOP many times over the years, and it always seemed like something useful for game programming, not web development. But it finally clicked when I found this user comment in the PHP manual, and I decided to give it a try at my next opportunity.
On the first project, I spent an extra 20 or 30 hours up front just thinking about how I wanted to use this technique. I ended up with a Base class that handles routine things like escaping quotes in database values and dealing with the discrepancy between saving a new record and updating an existing record. More importantly, I had to figure out what code would live in the Base class, what code would live in the other classes (like Order, Customer, etc.) and what code would live in the page scripts (like store_checkout.php). Eventually I found the right balance, and the second project went more quickly than it would have without OOP — a pretty fast return on investment. Since then, I’ve found updates and enhancements to be, maybe not quicker, but more reassuring because I know that all the related code is in one class.
My favorite thing about this approach is that it allows a greater degree of abstraction in my code. I always use Contemplate to separate design, content and functionality from each other. But OOP makes it easy to further separate functionality into data processing and data storage. It’s been easy to put SQL code only in the classes, and as a result, I only have to change a few files if my database structure changes. In fact, I quickly extended my Base class to store data either in a database or in a session — which is useful for something like a multi-page registration form that doesn’t create any records until the last page — and this distinction is completely abstracted from my page scripts, which only care that the data is being saved. If a new technology ever comes along to replace SQL databases in web development, and these sites are still around, it will be relatively easy to convert them.
I still have a couple adjustments to make in my programming style (for example, expanding my naming conventions to accommodate the variables I use for object instances) and I may be overusing static methods (which, beyond being organized into classes, are no different than traditional functions). But I’m sure that I’ll continue using this technique into the coming year and beyond.