forked from rahbirul/PHP_MongoDB_Packt_Book_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.php
75 lines (55 loc) · 1.83 KB
/
user.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
require_once('dbconnection.php');
require_once('session.php');
class User
{
const COLLECTION = 'users';
private $_mongo;
private $_collection;
private $_user;
public function __construct()
{
$this->_mongo = DBConnection::instantiate();
$this->_collection = $this->_mongo->getCollection(User::COLLECTION);
if ($this->isLoggedIn()) $this->_loadData();
}
public function isLoggedIn()
{
return isset($_SESSION['user_id']);
}
public function authenticate($username, $password)
{
$query = array('username' => $username, 'password' => md5($password));
$this->_user = $this->_collection->findOne($query);
if (empty($this->_user)) return False;
$_SESSION['user_id'] = (string) $this->_user['_id'];
return True;
}
public function logout()
{
unset($_SESSION['user_id']);
}
public function __get($attr)
{
if (empty($this->_user))
return Null;
switch($attr) {
case 'address':
$address = $this->_user['address'];
return sprintf('Town: %s, Planet: %s', $address['town'], $address['planet']);
case 'town':
return $this->_user['address']['town'];
case 'planet':
return $this->_user['address']['planet'];
case 'password':
return NULL;
default:
return (isset($this->_user[$attr])) ? $this->_user[$attr] : NULL;
}
}
private function _loadData()
{
$id = new MongoId($_SESSION['user_id']);
$this->_user = $this->_collection->findOne(array('_id' => $id));
}
}