-
Notifications
You must be signed in to change notification settings - Fork 281
/
Copy pathMongoDB.php
85 lines (75 loc) · 2.07 KB
/
MongoDB.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
<?php
namespace PhpConsole\Storage;
/**
* MongoDB storage for postponed response data.
*
* @package PhpConsole
* @version 3.1
* @link http://consle.com
* @author Sergey Barbushin http://linkedin.com/in/barbushin
* @copyright © Sergey Barbushin, 2011-2013. All rights reserved.
* @license http://www.opensource.org/licenses/BSD-3-Clause "The BSD 3-Clause License"
* @codeCoverageIgnore
*/
class MongoDB extends ExpiringKeyValue {
/** @var \MongoClient */
protected $mongoClient;
/** @var \MongoCollection */
protected $mongoCollection;
public function __construct($server = 'mongodb://localhost:27017', $db = 'phpconsole', $collection = 'phpconsole') {
$this->mongoClient = new \MongoClient($server);
if(!$this->mongoClient) {
throw new \Exception('Unable to connect to MongoDB server');
}
$this->mongoCollection = $this->mongoClient->selectCollection($db, $collection);
if(!$this->mongoCollection) {
throw new \Exception('Unable to get collection');
}
if (!in_array($collection, $this->mongoCollection->db->getCollectionNames())) {
$this->mongoCollection->db->createCollection($collection);
}
$this->mongoCollection->ensureIndex(array(
'expireAt' => 1,
), array(
'background' => true,
'name' => 'TTL',
'expireAfterSeconds' => 0,
));
}
/**
* Save data by auto-expire key
* @param $key
* @param string $data
* @param int $expire
*/
protected function set($key, $data, $expire) {
$this->mongoCollection->update(array(
'key' => $key
), array(
'key' => $key,
'data' => $data,
'expireAt' => new \MongoDate(time() + $expire)
), array(
'upsert' => true
));
}
/**
* Get data by key if not expired
* @param $key
* @return string
*/
protected function get($key) {
$record = $this->mongoCollection->findOne(array('key' => $key));
if($record && is_array($record) && array_key_exists('data', $record)) {
return $record['data'];
}
}
/**
* Remove key in store
* @param $key
* @return mixed
*/
protected function delete($key) {
return $this->mongoCollection->remove(array('key' => $key));
}
}