Question

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:

  1. Create a getUsers() method which can take multiple ID's and does one query.
  2. 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.

Was it helpful?

Solution

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.

OTHER TIPS

use the first one like 
1)Create a getUsers() method which can take multiple ID's and does one query.
because it make efficient to your application rather than use the second one ,

if you use the second one it create a instance each time, it affect your application performance   so only here i suggest the first one 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top