Search code examples
phpobjectsingletoninstances

Usefulness of loading instances in OO PHP?


I was asked to do a project in PHP and to make sure it was object oriented. I've done OO and I've done PHP, but never both.

The main benefit of OO PHP (outside of inheritance/polymorphism) seems to be code organization. That's fine; I'm doing that. But where I get stuck is if I should actually be creating instances for every "object."

To me (and maybe I'm being naive here), a web app is all about making very short, stateless requests to alter or retrieve records in a database. The objects can't persist between requests. So it feels rather pointless to load data from the database, construct an object from that data, make a small update, save the data from the object back to the database, and then throw the object away. The loading/saving code seems to be a lot of work for nothing. [clarification: a waste of development time, not processing time... not too concerned about overhead]

The alternative is to have a bunch of singletons (or classes with static methods) that just provide a nice, organized abstraction layer to the database layer. I guess writing code in this manner just doesn't feel truly OO. Am I missing something or is that style fine?


Solution

  • Singletons are essentially just global variables with some namespace sugar added in. There are a few main benefits to programming with objects and classes that you just don't get from straight procedural programming. One is inheritance, as you mentioned. Another is the namespacing - you can have a code to compress the lot into a single include file (more meaningful in interpreted languages like PHP than in compiled languages).

    Objects are essentially a collection of functions with a shared state (though singletons make that a global state. Beware.) As you pointed out the benefit is mostly that that state is transparently shared by the functions without needing to explicitly pass it every single call. If you have various functions per request operating on shared data and wish them to be specialized forms of a general set of functions, OOP is probably a good fit.

    Since you have been tasked to "make sure it is object oriented", I'd take some time to consider common groups of functions, generalizations of same, etc.

    In the end the setup/teardown time of the objects isn't too bad - and it might even save some development time in the future if you do a good job.