I’ve recently started trying to implement a better way to structure my code. It’s almost as big of a shift as when I switched from procedural to object-oriented programming. The funny thing is that it isn’t a new approach at all. It’s just the true application of OOP. I’ve been doing it for years in assignments for the various Java and C++ classes I’ve taken at Fullerton and Cal Poly. It’s normal and intuitive. Each class represents one data structure. Duh.
Only, that’s not how I’ve been writing my PHP code. Not exactly, anyway. My PHP has been written in a more “database-oriented” style, rather than an object-oriented style. All of my classes were built around database operations—usually dealing with sets of data rows—rather than individual objects. If you’ve ever written a class for a data structure, you know that one of the most common features is a set of member variables that correspond to the object properties. My classes never had those, mainly because PHP’s associative array structure can represent objects very nicely.
This approach leads to only a partial representation of the object. I would create only a single instance of each class, and use that to interface with the database and perform all of the operations. You can get by this way with PHP, because it’s a language that doesn’t (usually) create interactive programs that reside in memory; each time a script runs, it’s a single hit to a webpage rather than a persistent instance. But it still leaves things a bit convoluted from a design standpoint. At least, that’s what I’m beginning to discover. Classes need to define objects and their relevant properties and operations, nothing else.
So, I’m working on a library that will help separate database stuff from object stuff, so that objects can be objects and database operations happen separately, but the database aspect of things can be attached cleanly and simply no matter what the objects look like. Hopefully I’ll have some code to give away soon, once I’m happy with it.
I love learning new things.