Reputation: 10875
I've been working on a website, and currently at the stage of login/session handling.
I want to know what is a better design in your opinion. (this website will be available to the public, so it should be user-friendly too).
P.S. sorry if this is not the correct php 'conventions', I am used to c/c++ programming.
Design #1:
define("LOGGED_IN", false);
define("USERNAME", "Guest");
define("PASSWORD", "");
define("PLAYER_ID", -1);
...
if (!LOGGED_IN) {
header("Location: login.php");
} else {
...
}
...
if ({condition for successful login}) {
define("LOGGED_IN", true);
define("USERNAME", "AJ");
define("PASSWORD", "nottellingu");
define("PLAYER_ID", 1);
}
...
printf("Hi, %s. Have a nice day.", USERNAME);
Design #2:
class user {
private $id;
private $logged_in;
private $username;
private $password;
public function __construct($id, $username, $password, $logged_in = false) {
$this->id = $id;
... blablabla
}
public function get_id() {
return $this->id;
}
... blablabla (pretend i declared all needed functions)
}
...
if ({condition for successful login}) {
$id = get_userid($_SESSION['USERNAME']]);
$user = new user($id, $_SESSION['USERNAME'], $_SESSION['PASSWORD'], true);
}
...
printf("Hi, %s. Have a nice day.", $user->get_username());
You can give me your designs aswell.
Thanks
Upvotes: 1
Views: 92
Reputation: 19979
IMO, design approach #2 is better. Not only do you get encapsulation for anything user related, but it is also modular, so you can refer to any of the attributes anywhere throughout your codebase.
You may also want to do some googling and see if there is a stand-alone user login system you can use, vs. re-inventing the wheel.
Upvotes: 1
Reputation: 12059
I think either way is okay. It really just depends on what you are trying to accomplish. If you are going to be consistently pulling user info, a class might be better. If you are going to just need a few basic things like ID and name and whether or not they are logged in, the first option is simpler and will work fine for that purpose.
There is no point to over complicating something when you can do it a simple way and be done with it.
Upvotes: 1