forked from canni/YiiMongoDbSuite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEMongoHttpSession.php
101 lines (85 loc) · 1.94 KB
/
EMongoHttpSession.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
class EMongoHttpSession extends CHttpSession
{
public $connectionID;
public $collectionName;
private $_db;
private $_collection;
public function getUseCustomStorage()
{
return true;
}
public function getDbConnection()
{
if($this->_db !== null)
return $this->_db;
else if(($id = $this->connectionID) !== null)
{
if(($this->_db = Yii::app()->getComponent($id)) instanceof EMongoDB)
return $this->_db;
else
throw new EMongoException('EMongoHttpSession.connectionID is invalid');
}
else
{
if(($this->_db = Yii::app()->getComponent('mongodb')) instanceof EMongoDB)
return $this->_db;
else
throw new EMongoException('EMongoHttpSession.connectionID is invalid');
}
}
public function openSession()
{
$db = $this->getDbConnection();
$db->connect();
$this->_collection = $db->getDbInstance()->{$this->collectionName};
return true;
}
public function destroySession($id)
{
$this->_collection->remove(array('_id'=>$id));
return true;
}
public function gcSession($maxLifetime)
{
$db = $this->getDbConnection();
$db->connect();
$db->getDbInstance()->{$this->collectionName}->remove(array(
'expire'=>array('$lt'=>time())
));
return true;
}
public function readSession($id)
{
$doc = $this->_collection->findOne(array(
'_id'=>$id,
'expire'=>array('$gt'=>time())
));
return $doc !== null ? $doc['data'] : '';
}
public function writeSession($id, $data)
{
// exception must be caught in session write handler
// http://us.php.net/manual/en/function.session-set-save-handler.php
try
{
$expire = time() + $this->getTimeout();
if($this->_collection===null)
{
$db = $this->getDbConnection();
$db->connect();
$this->_collection = $db->getDbInstance()->{$this->collectionName};
}
$this->_collection->save(array(
'_id'=>$id,
'expire'=>$expire,
'data'=>$data,
));
}
catch(Exception $e)
{
return false;
}
return true;
}
}