HiveBrain v1.2.0
Get Started
← Back to all entries
snippetphpMinor

How to properly make a user class with a session

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
properlyuserwithmakesessionhowclass

Problem

So I am working on a LMS project and I have a User class that will handle everything about the user such as registration, login, showing list of courses that they are subscribed to, etc.

User.class.php

``
class User {
protected $_firstName;
protected $_lastName;
protected $_email;
protected $_username;
protected $_password;
protected $_createdOn;
protected $_userLevel;
protected $_salt = '}$YY lGC6&wib=w{dpqgzXv>{)A3w)5@mi
/Q7HK|/GwZ6)K_firstName; }

public function setFirstName($value) {
$this->_firstName = $value;
if (empty($value)) {
setError('firstName', 'Enter your first name.');
} else if (strlen($value) _lastName; }

public function setLastName($value) {
$this->_lastName = $value;
if (empty($value)) {
setError('lastName', 'Enter your last name.');
} else if (strlen($value) _email; }

public function setEmail($value) {
$this->_email = $value;
$pattern = '!^.{1,}@.{2,}$!i';
if (empty($value)) {
setError('email', 'Enter your email.');
} else if (substr_count($value, '@') != 1 and !preg_match($pattern, $value)) {
setError('email', 'The email you provided is not valid.');
}
}

public function getUsername() { return $this->_username; }

public function setUsername($value) {
$this->_username = strtolower($value);
if (empty($value)) {
setError('username', 'Enter your username.');
} else if (strlen($value) _password; }

public function setPassword($value) {
$this->_password = $value;
if (empty($value)) {
setError('password', 'Enter a password.');
} else if (strlen($value) _password != $value) {
setError('confirmPassword', 'This does not match your password.');

Solution

First of all I would split the User class in 2 or 3 classes User, Authentication and Registration. The setter error could easily become Exceptions, which you could collect in you Registration class.

At the end you will have a smaller User object you can attach to the session.

Please also check http://www.phpbuilder.com/columns/validating_php_user_sessions.php3 for some hint regarding session validation.

Context

StackExchange Code Review Q#22738, answer score: 2

Revisions (0)

No revisions yet.