Design Practice Retrieve Multiple Users - PHP
Posted
by pws5068
on Stack Overflow
See other posts from Stack Overflow
or by pws5068
Published on 2010-04-22T15:01:34Z
Indexed on
2010/04/22
15:03 UTC
Read the original article
Hit count: 349
Greetings all, I'm looking for a more efficient way to grab multiple users without too much code redundancy.
I have a Users class, (here's a highly condensed representation)
Class Users {
function __construct() { ... ... }
private static function getNew($id) {
// This is all only example code
$sql = "SELECT * FROM Users WHERE User_ID=?";
$user = new User();
$user->setID($id);
....
return $user;
}
public static function getNewestUsers($count) {
$sql = "SELECT * FROM Users ORDER BY Join_Date LIMIT ?";
$users = array();
// Prepared Statement Data Here
while($stmt->fetch()) {
$users[] = Users::getNew($id);
...
}
return $users;
}
// These have more sanity/security checks, demonstration only.
function setID($id) { $this->id = $id; }
function setName($name) { $this->name = $name; }
...
}
So clearly calling getNew() in a loop is inefficient, because it makes $count number of calls to the database each time. I would much rather select all users in a single SQL statement.
The problem is that I have probably a dozen or so methods for getting arrays of users, so all of these would now need to know the names of the database columns which is repeating a lot of structure that could always change later.
What are some other ways that I could approach this problem? My goals include efficiency, flexibility, scalability, and good design practice.
© Stack Overflow or respective owner