PHP class with property which can be either an int or an array
I have a class (say Product) with a property (say product_id) and has methods to retrieve information from multiple database tables for given product ID. Now I want the class methods to handle one product ID as well as an array of product IDs (in order to save the number of queries). Also the output will vary depending on the input i.e. for array as input, I'll have as output an array indexed with product ids, whereas for a single ID, I might not need this array.
What is the clean way to design such a class?
Here are a couple of things I've thought of:
Have separate methods with indicative names for single and multip开发者_Go百科le ids (clean but duplication)
Have only one method for both types of input, check input type...process...format output as per the input (not really clean)
Internally, always work with an array of values. If there's only one value in the array, so be it, but that doesn't need to change your logic at all.
For input/output, you may want to make your methods accept a single value, which you're going to turn into an array:
public function foo($val) {
$val = (array)$val;
...
}
And/or, you might create a "singular convenience wrapper" that just makes it clear that it returns or accepts single results:
public function foos(array $vals) {
...
return /* array of elements */;
}
public function foo($val) {
return current($this->foos(array($val)));
}
精彩评论