views:

309

answers:

4

Hi,

I am wondering whats the best practices regarding functions and objects. For example I want to perform an action called tidy. It will take my data as input and tidy it and return it.

Now I can do this in two ways. One using a simple function and the other using a class.

Function: $data = tidy($data);
Class:
$tidy = new Tidy();
$data = $tidy->clean($tidy);

Now the advantage in making it a class is that I do not have to load the class before. I can simply use the autoload feature of php to do so.

Another example is the database class. Now everyone seems to be using a separate class for db connectivity. But we usually have a single object of that class only. Isn't this kind of contrary to the definition of class and objects in a sense that we are using the class only to intantiate a single object?

I kind of dont understand when to use a function and when to use a class. What is the best practice regarding the same? Any guidelines?

Thank you, Alec

A: 

I'd personally make a 'data' object that handles data then have a tidy method under it.

This pattern will allow the number of tasks you do on data to expand while containing it all in a nice little self-contained chunk.

Adam Hawes
+1  A: 

For something that does one thing, and only one thing, I'd just use a function. Anything more complex, and I'd consider using an object.

I took the time to poke through some piles of (arguably ugly and horrible) PHP code and, really, some things could have been done as objects, but were left as functions. Time conversions and string replacements.

hydrapheetz
A: 

For your case, I'd make it a function, possibly a static function in something like a "util" class (for which the only purpose of the class is to act like a namespace - it'll group all your random useful methods together). As a rule of thumb, only use an object if it needs to store some data that needs to live between multiple function calls. That's why the database methods are made to be part of an object, because they store a database handle which is used between multiple function calls. Yes, there only ever is one database object, but having it as an object groups all the database-related stuff into one place, making it easier to maintain and keep bug-free.

Ray Hidayat
Yeah, I have a lot of 'util' classes, which are more or less a collection of functions which are related.
Philip Morton
+1  A: 
  • Functions typically do one specific task.

  • Objects represent something that have tasks associated with it. (methods)

Use a function for tidy. Plain and simple. ;-)

Evan Fosmark