User classes
Posted: Fri Aug 24, 2007 7:26 pm
While working with MVC, I'm wondering how people work in their user credentials.
My theory is have a user model, something like the following.
Then to get the current user.
To register a user.
To update a user.
Are we allowed to do certain things.
Comments, suggestions?
My theory is have a user model, something like the following.
Code: Select all
<?php
define('ACCESS_ADMIN',2);
define('ACCESS_MOD',1);
class UserModel {
private $data=false;
public function __construct($value='',$key='username') {
global $db;
if(func_num_args()) {
$q = $db->execute('SELECT * FROM users WHERE `'.$key.'`=\'' . addslashes($value)."'");
if($q->numrows == 0) {
throw new Exception('Unable to find user');
} else {
$this->data = $q->fetchArray($q);
}
}
}
static function Login() {
global $db;
if(isset($_SESSION['userid'])) {
$user = new UserModel($_SESSION['userid'],'id');
if($user->password == $_SESSION['password']) {
return $user;
} else {
unset($_SESSION['userid']);
unset($_SESSION['password']);
}
}
$in = input(array('login_username'=>FILTER_UNSAFE_RAW,'login_password'=>FILTER_UNSAFE_RAW));
if($in['login_username']) {
$user = new UserModel($in['login_username']);
if($user->password == md5($in['login_password'])) {
$_SESSION['userid'] = $user->id;
$_SESSION['password'] = md5($user->password);
} else {
throw new Exception('Invalid Username/Password');
}
}
}
public function __get($key) {
return $this->data[$key];
}
public function __set($key,$val) {
$this->data[$key] = $val;
}
public function commit() {
if(isset($this->data['id'])) {
$sql = 'UPDATE users SET ';
foreach($this->data as $k=>$v) {
if($k != 'id') {
$sql .= '`'.$k.'`=\'' .addslashes($v).'\',';
}
}
$sql = substr($sql,0,-1);
$sql .= ' WHERE id='.intval($this->data['id']);
$q = $db->execute($sql);
return $q->affectedRows;
} else {
$fields = '';
$values = '';
foreach($this->data as $k=>$v) {
$fields.='`'.$k.'`,';
$values .= "'".addslashes($v)."',";
}
$fields = substr($fields,0,-1);
$values = substr($values,0,-1);
$q = $db->execute('INSERT INTO users ('.$fields.') VALUES ('.$values.')');
return $db->insertID;
}
}
function checkAccess($access) {
return $this->data['access'] >= $access;
}
}
?>Then to get the current user.
Code: Select all
$user = UserModel::login();Code: Select all
$user = new UserModel();
$user->username = 'administrator';
$user->password = md5('something');
$user->email = 'whatever';
$user->commit();Code: Select all
$user = UserModel::login();
$user->email = 'someemail@blah.com';
$user->commit();Code: Select all
$user = UserModel::login();
if($user->checkAccess(ACCESS_MOD)) {
echo 'Your a admin';
}