开发者

PHP class with property which can be either an int or an array

开发者 https://www.devze.com 2023-03-27 04:35 出处:网络
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 pro

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:

  1. Have separate methods with indicative names for single and multip开发者_Go百科le ids (clean but duplication)

  2. 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)));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号