我的User类中有一个静态getUser($ userID)方法,它查询数据库并返回给定用户ID的User对象。
有时,我需要同时获得多个用户。 我想出了两个选择:
创建一个getUsers()方法,该方法可以获取多个ID并进行一次查询。 创建一个getUsers()方法,该方法可以使用多个ID但使用getUser方法(多个DB查询)。在这两种情况下,我将返回一个User对象数组。 但是如果userID有效或不存在会发生什么? 只是从阵列中排除那个用户? 看起来很奇怪。
所以得到答案会很棒:
我应该使用选项1还是2? 如果用户ID无效,应该怎么办,忽略它? 或抛出异常?随意批评使用静态方法getUser(),我不知道在哪里放置该方法,谢谢。
I have a static getUser($userID) method in my User class which queries the database and returns a User object for the given user ID.
At times, I have multiple users I need to obtain at the same time. I've come up with two options:
Create a getUsers() method which can take multiple ID's and does one query. Create a getUsers() method which can take multiple ID's but uses the getUser method (multiple DB queries).In both cases, I will be returning an array of User objects. But what should happen if a userID is in valid or doesn't exist? Just exclude that User from the array? Seems weird.
So it would be great to get answers to:
Should I use option 1 or 2? What should happen in the event of an invalid user ID, just ignore it? Or throw an exception?Feel free to critique the use of a static method getUser() too, I don't know where else to put that method, thanks.
最满意答案
这是我认为你应该优化的东西,直到它成为一个瓶颈。
如果你拆分它会更清洁。 事实上,我甚至建议您创建另一个文件夹并将其称为集合。 在那里你有一个UserCollection,允许你迭代不同的用户集。 使用current()方法,然后返回一个用户对象。
对于getUser()部分,我会将像用户对象这样的东西放入一个名为entities的文件夹中。 这些对象处理单个用户的CRUD操作,而集合则用于返回用户组(或单个用户)。
在实体部分中,如果找不到某些内容,则可以抛出异常。 该集合应仅返回有效的ID。
作为旁注,当您使用迭代器时,您还可以在集合中混合使用不同的对象,这在某些情况下非常有用。
This is something I don't think you should optimize until it becomes a bottle neck.
It is much cleaner if you split it up. In fact, I would even recommend that you create another folder and call it collections for example. In there you have for example a UserCollection that allows you to iterate over different sets of users. With the current() method you then return a user object.
For the getUser() part, I would put things like a user object into a folder called entities. Those objects handle the CRUD operations of a single user while the collections are there to return sets of users (or a single user).
In the entity part you can throw an exception if something is not found. The collection should only return valid IDs.
As a sidenote, you can also mix different objects in your collection when you use iterators, this can be pretty useful in some cases.
更多推荐
发布评论