PHP Programming Practices – Multiple Parameters vs Single Object Parameter

PHPprogramming practices

I have an Entity Student with following properties – (name, joinedOn, birthday, age, batch, etc.) and a function fetchStudents(<params>).
I want to fetch students based on multiple filters.

In my method I have two ways to pass filters.

  1. Pass all filters as params to the method
  2. Make a class StudentCriteria with filters as fields and then pass
    the object of this class

While working in java I always go with the second option but recently I'm working in php and I was advised to go with the first way. I am unable to figure out which way is better in maintaining the code, reusability and performance wise. Thanks.

Best Answer

I personally don't like having too many optional arguments if I can get away with it. I can find it quite hard to read and when you end up passing things like

getOption($option1, "",0,"")

where the method declaration is actually something like (of course real parameter names would be better named)

getOption($myoption, $textStr, $numberOf, %description = "", $name = "", $typeOf = 0)

It's hard to know from reading this what exactly the values are and also what you are setting or leaving out. Every time I want to call that method I have to be very careful to set the right parameters in the right place.

A possible alternative is to use something like the Builder pattern where you are building up the criteria you wish to add explicitly. For those parameters which are required you make part of the constructor. For those optional ones you have a method to add.

Something like:

class StudentEnrollmentCriteriaBuilder {
   function __construct($id) {
      // id is always required for this criteria
   }

   function getCriteria() {
      // return the built up criteria
   }

   function addNameFilter($name) {
      // add the name to the filter
      return $this;
   }

   function addSexFilter($sex) {
      // add sex type as a filter

      return $this;
   }

   // etc
}

I guess you could then use it like

$criteria = new StudentEnrollmentCriteriaBuilder ($id);

$query = $criteria.addNameFilter('bob').addSexFilter('M').getCriteria();

// do stuff

Each method would be responsible for adding the filter if valid. So I guess in the case of the name if it was an empty name you would not add it as a filter etc as it wasn't required, or throw an exception etc etc

If it came down to it, where there are many properties I prefer the object option. If some are required at least make them part of the constructor. If you at least made the optional ones method based you could add validity checking on the data at that point, or leave it up to the user of the object to do.

Just my 1 1/2 cents.