Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be an instance of a class in php?

In PHP 5.2.x, mySQL 5.x

Im having a bit of an issue wrapping my head around what should and should not be an instance of a class in php because they are not persistent once the page is rendered.

Say I have a list of comments. To me, it would make sense that every comment be its own object because I can call actions on them, and they hold properties. If I was doing this in another language (one that has persistent state and can be interacted with), I would do it that way.

But it seems wasteful because to do that I have a loop that is calling new() and it would probably mean that I need to access the database for each instance (also bad).

But maybe im missing something.

Php just seems different in how I think about class and objects. When should something be a class instance, and when not?

like image 871
Adam Meyer Avatar asked Oct 24 '22 11:10

Adam Meyer


1 Answers

This is a subjective issue, so I'll try to gather my thoughts coherently:

Persistence in PHP has sort of a different meaning. Your thinking that each comment should be an object because comments have actions which can be performed on them seems correct. The fact that the objects won't persist across a page load isn't really relevant. It isn't uncommon in PHP to use an object in one script, which gets destroyed when the script completes, and then re-instantiate it on a subsequent page load.

Object-oriented programming provides (among other things) code organization and code reuse. Even if an object is only really used once during the execution of a script, if defining its class aids in program organization, you are right to do so.

You usually needn't worry about resource wastefulness until it starts to become a problem; if your server is constantly taxed to where it degrades your user experience or limits your expansion, then it is time to optimize.

Addendum:

Another reason defining a class for your comments is that doing so could pay dividends later when you need to extend the class. Suppose you decide to implement something like a comment reply. The reply is itself just a comment, but holds some extra attributes about the comment to which it refers. You can extend the Comment object to add those attributes and additional functionality.

like image 63
Michael Berkowski Avatar answered Oct 31 '22 10:10

Michael Berkowski