I have built a User class that attempts to lookup the ID for a user in a MySQL database. If it finds it, it sets the variable SQL_ID to this value, otherwise it leaves it empty.
A separate method (IsValid), called later, returns a boolean telling me if the user, in fact does exist.
I was curious if anyone else would like to comment on my design here, and perhaps offer a more elegant solution. I admit that PHP is not my primary language, and I may be feeling a little OCDish after spending too much time in a non-statically typed language. Perhaps I am seeking validation that this design is sane.
// User -> class for passing around user information. Should only pass around the UserID (a unqiue SQL ID), for security reasons, in a Session object.
class User {
private $SQL_ID = "";
//@todo: Get the User object to actually talk to the other classes. Lol.
public function __construct($Username, $Password) {
// Probably want to Base64 encode the values going into and out of the MySQL database, to prevent a SQL Injection attack.
$query = "SELECT [UserID] FROM [Users] WHERE [Username] = '" . base64_encode($Username) . "' AND [Password] = '" . base64_encode($Password) . "';";
$data = SQL::DataQuery($query);
$this->SQL_ID = $data["UserID"];
}
// Boolean function to tell us if we have a valid user. Might be able to merge this into the constructor.
public function IsValid() {
if($this->SQL_ID == "") {
return false;
}
return true;
}
public function GetUserID() {
return $this->SQL_ID;
}
// private $Query = "SELECT [UserID] FROM [Users] WHERE [Username] = '' AND PASSWORD = '';"; // Prototype User query (for selecting a UserID).
}
I don’t think you should have a User object unless the login has been successful. I would use another class (named something like Authenticator) that would be responsible for checking the username and password against the database and returning a User object only if a valid user is found.