This is a simple User class that I'm using throughout the application for anything related to the users. To tell if a user is logged in or not, I check the presence of the userID in the $_SESSION. When I'm logging in the user, I simply set the $_SESSION["userID"] equal to the ID of the user.
class User{
protected $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function getID()
{
if(!$this->isConnected()) return 0;
return $_SESSION["userID"];
}
public function isConnected()
{
return !empty($_SESSION["userID"]);
}
public function login($username, $password)
{
$q1 = $this->pdo->prepare("SELECT * FROM users WHERE username = ?");
$q1->execute([$username]);
$user = $q1->fetch();
if(empty($user)) return false;
if(!password_verify($password, $user->password)) return false;
$_SESSION["userID"] = $user->id;
$_SESSION["username"] = $user->username;
return true;
}
}
I'm putting everything in a class just so that it's organized and easily accessible, but I'm pretty sure I'm not doing this properly. I presume that the correct way to handle this is to use properties for the class (example: $isConnected, $id) and change them when the user logs in/logs out.
However, I'm not sure how I would do that and avoid overwriting the user object every time the script loads (page refresh), so at the moment I'm doing it like that.
It works fine, but I really feel like I'm missing the point of OOP here. I'm a beginner when it comes to OOP with PHP, so please don't be too harsh! I'd really like some input from experienced developers.