我构建了一个User类,它试图在MySQL数据库中查找用户的ID。如果找到它,它会将变量SQL_ID设置为此值,否则将其保留为空。
一个单独的方法(IsValid),稍后调用,返回一个布尔值,告诉我用户是否确实存在。
我很好奇是否有人想在这里评论我的设计,并且可能提供更优雅的解决方案。我承认PHP不是我的主要语言,在用非静态类型的语言花费太多时间后,我可能会感到有些OCDish。也许我正在寻求验证这种设计是否合理。
// 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).
}
答案 0 :(得分:1)
除非登录成功,否则我认为您不应该拥有User对象。我会使用另一个类(类似于Authenticator)来负责检查数据库的用户名和密码,并仅在找到有效用户时返回User对象。