Skip to content
Advertisement

PHP Classes: Should I use 2 classes or 1?

I am currently trying to make a class that deals with a survey in PHP (Drupal). So far I have this:

JavaScript

This is great, I can create a new instance of Survey, set the properties, and call save on it.

However, I also want to be able to have methods that retrieve the results of these surveys from the DB and act on them, giving me various numbers. It doesn’t feel right to have those methods in the class Survey, because they are actually multiple Surveys. However they are related, and may also return instances of Survey so not sure if they should be a completely separate class. What is the best thing to do here?

BTW I don’t care if its a Drupally answer.

Thanks, Amshad

Advertisement

Answer

As with anything, there are many approaches with their own advantages and disadvantages.

My (current) preference is to combine class methods (static) and object methods for handling groups of objects and individual objects, respectively.

Consider the following code:

JavaScript

You can use the static methods to work with groups of objects. You could even have a static array holding a reference to each loaded survey.

Another option is to have a “Surveys” class whose purpose is to work with groups of surveys. The previous approach feels cleaner to me.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement