PHP Object-Oriented – Multiple Object Instantiation Best Practices

databaseobject-orientedPHP

I am trying to get my head around object oriented programming as it pertains to web development (more specifically PHP).

I understand inheritance and abstraction etc, and know all the "buzz-words" like encapsulation and single purpose and why I should be doing all this.

But my knowledge is falling short with actually creating objects that relate to the data I have in my database, creating a single object that a representative of a single entity makes sense, but what are the best practises when creating 100, 1,000 or 10,000 objects of the same type.

for instance, when trying to display a list of the items, ideally I would like to be consistent with the objects I use, but where exactly should I run the query/get the data to populate the object(s) as running 10,000 queries seems wasteful.

As an example, say I have a database of cats, and I want a list of all black cats, do I need to set up a FactoryObject which grabs the data needed for each cat from my database, then passes that data into each individual CatObject and returns the results in a array/object – or should I pass each CatObject it's identifier and let it populate itself in a separate query.

Best Answer

Creating 100, 1 000 or 10 000 similar objects is not itself an issue (unless the object itself is huge). If you find yourself creating thousands and thousands of objects, ask yourself if you really need to.

If you're loading Cat objects, one per cat stored in the database, do you need to load all the 500 000 cats, for example? Why? You can't display them on the screen: it wouldn't be particularly useful. If you need to process them, is preloading everything the best way to do?

When you need a list of black cats, you don't load every cat available. What you do is to limit, at database level (for example with a where [color] = @color), the results you get, and you build objects corresponding to black cats only.

Indeed, this can be done in a factory which will contain a method which takes a specific color and returns the cats of this color.

Doing a query per cat, on the other hand, is a terrible approach. The fewer queries you do, the better. That's why your suggestion to use a factory was a good idea.

Related Topic