I have a search function that queries the database and has ~15 optional parameters. Obviously this is not pretty and calling it is a bit of a mess. PHP does not allow overloading methods so I've just been creating huge function signatures.
Elsewhere I've seen suggestions such as creating a parameter class: Disadvantages of using a lot of parameters
But this seems too heavy. I could pass in an associative array, but while this reduces the number of parameters I believe it is less easy to follow as there is no built in documentation stating what keys should exist in the array.
Is there any other way to handle this gracefully? Typically in other languages I would have a really ugly private
method that takes up to a dozen parameters and then create public
methods of the same name which accept a subset of those parameters and internally call the private method.
In PHP, you can use associative array:
Or properties of the object that the function is being called on (if it makes sense). PHPMailer send mails like this:
And it has many more optional parameters. It could as well use a method with hundred parameters, but this is much more readable.
EDIT: These solutions also better support optional parameters. In case of properties it is straightforward, in case of associative array, you can merge the array with array of default values.