Long story short, I would like to use OOP for my new PHP project. It has a "login" requirement (i.e. user will first need to enter the username and password (login.php), if it's correct, it will be redirected to index.php and then fetch some products information). Also there will be a settings page that allows user to change the password, and email if necessary.
In summary:
- When user attempts to login, the program will check if the username, password entered is correct or not. If it's correct, username (or maybe the whole
User
object) will be saved in the$_SESSION
. - When the user settings page is loaded, it will display all user related fields on screen (i.e. by using
$_SESSION
). - The user can make changes in the user settings pages and data should be saved to the database.
I have this User
class:
class User {
private $username;
private $email;
private $hashed_password;
private $dob;
...
public __construct($user) {
$this->username = $user;
}
public function isPasswordCorrect($userenteredpassword) {
$this->loadFromDatabase();
//hashed userenteredpassword, compare it against $this->hashed_password
//if it matches, return true, otherwise return false.
}
public function saveToDatabase() {
//save info to database
}
public function loadFromDatabase() {
$row = select fields from user table where username = $this->username limit 1
if ($row is found) {
$this->hashed_password = $row['hashed_password'];
$this->dob = $row['dob'];
...
}
}
}//class
However, I was told that the function isPasswordCorrect
shouldn't be implemented inside class User
, as it is not its job to determine whether the login is valid or not. Instead, I should create an authService
helper and use it to determine whether the login is good or not.
Now, this makes me wonder if the rest of my User
class design is okay or not. If I shouldn't put the password checking function in the User
class, then is it okay to implement the database related functions in User
? How do I determine which function should be implemented in the class? Should I follow Single Responsibility principle? Wouldn't it be too extreme?