joshwoodward
joshwoodward

Reputation: 201

PHP Objects + MySQL: How far to go with modeling select queries?

I have a large PHP project that I started a decade ago, and out of inertia, it's very functional in style. I've been using OOP for new features, and it's been making development a lot easier.

But I've been frequently running into a dilemma. Let's take a calendar as an example. Using objects makes total sense to model the database concept of a calendar category, a time range, the display model, etc. But when it comes to grabbing actual events out of the database, it feels more natural to me to just use the array of hashes that come out of the MySQL library. The overhead of creating hundreds, possibly thousands, of objects to model the results of a select query seems like overkill. It'd be nice to have them as objects, but at what cost?

What are the best PHP OOP practices for selecting potentially large numbers of rows from a database?

Upvotes: 0

Views: 173

Answers (1)

Codecraft
Codecraft

Reputation: 8296

My approach is somewhat similar I think to Wing's comment.

I have an object which I use throughout all projects that I can run a custom SQL query through and have it return an array; so it can be used in a way not too dissimilar to how I am (and you are) used to.

I build objects on top of that for particular projects where I need to run the same / similar queries a lot, I still make sure it returns something sensible (usually an array with field names as keys, why fix what isn't broken?)

It definitely makes a lot more sense to work with common queries in this way - so when you expand/change the data structure, you don't break 100's of pages, you just fix one object. Having the level above that you can run custom queries is most helpful for the 'one off' situations so you're not building new objects to handle every little thing.

Upvotes: 1

Related Questions