PHP 类的属性可以是 int 或数组
我有一个带有属性(例如product_id)的类(例如Product),并且具有从多个数据库表中检索给定产品ID 的信息的方法。现在我希望类方法能够处理一个产品 ID 以及一组产品 ID(以节省查询数量)。此外,输出将根据输入而变化,即对于数组作为输入,我将使用产品 id 索引的数组作为输出,而对于单个 ID,我可能不需要这个数组。
设计这样一个类的干净方法是什么?
以下是我想到的几件事:
使用单独的方法,为单个和多个 id 提供指示性名称(干净但重复)
对于两种类型的输入只有一种方法,检查输入类型...处理...根据输入格式化输出(不是很干净)
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 multiple 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在内部,始终使用值数组。如果数组中只有一个值,那就这样吧,但这根本不需要改变你的逻辑。
对于输入/输出,您可能想让您的方法接受单个值,您将把它转换成数组:
和/或者,您可能创建一个“单一便利包装器”,它只是明确它返回或接受单个结果:
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:
And/or, you might create a "singular convenience wrapper" that just makes it clear that it returns or accepts single results: