Morphing from procedural PHP to OOP

I have a small number of PHP/MySQL web sites written in procedural code. I’ve used a fair number of functions, arrays, etc., and have been able to re-use many of them on each site, albeit with some modification/improvement each time. Much of the code was initially based on ‘Build your own Database driven web site’ (Kevin Yank, Sitepoint, 4th Edition), but has been greatly extended.

I would like to re-write the sites to use OOP (in the expectation that this will make the code more easily re-usable and maintainable etc.). I have been looking at OOP for some time, and have some understanding of it (but very little practical experience). I never get beyond reading about it. I have come to realise that my problem is that I’ve no idea where to start, and that is the bit the tutorials don’t tell you.

Despite the reading, it’s not clear to me what to select as my objects. Typically tutorials pick on books or CDs, but my web sites don’t sell anything so tangible. Most of mine are selling accommodation (selling bed-nights, if you like).

Does it make any sense to choose as my objects the records I store in the database? In that case my commonly used objects might be ‘nights’, bookings’, ‘guests’, and others would be ‘rates’ (tariff), ‘seasons’ etc.

Developing that idea a bit further, I’d have a ‘booking’ class, and each actual booking (reservation) would be an object of that class, with properties like number of nights, number of people, etc. Does that begin to make sense?

I’m not expecting a specific answer here, but looking for guidance as to how I decide what objects (or classes) I require.

Absolutely! You’d have classes that represent the structure of your tables (with getters and setters for each column), and a services (also being implemented as classes) to map and persist instances of those classes to the database.

You might check out some popular frameworks such Symphony2 or Laravel for inspiration – or just use one of them frameworks for your projects instead of reinventing the wheel. :-) These can be a bit overwhelming at first, but they’re extremely well documented (the two I mentioned at any rate), and by learning these you’ll get a better understanding of how to structure your application according to the MVC pattern in general.

Thank you, that is helpful and reassuring. I’ll look into using a framework. I don’t want to reinvent the wheel, but I have an aversion to using ‘black boxes’ where I don’t really know what goes on inside.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.