1: <?php
2: 3: 4: 5: 6: 7:
8:
9: namespace Wei;
10:
11: 12: 13: 14: 15:
16: class MongoCache extends BaseCache
17: {
18: 19: 20: 21: 22:
23: protected $host = 'localhost';
24:
25: 26: 27: 28: 29:
30: protected $port = 27017;
31:
32: 33: 34: 35: 36:
37: protected $object;
38:
39: 40: 41: 42: 43:
44: protected $db = 'cache';
45:
46: 47: 48: 49: 50:
51: protected $collection = 'cache';
52:
53: 54: 55: 56: 57:
58: public function __construct(array $options = array())
59: {
60: parent::__construct($options);
61:
62: if (!$this->object) {
63: $mongo = new \MongoClient($this->host . ':' . $this->port);
64: $this->object = $mongo->selectCollection($this->db, $this->collection);
65: }
66: }
67:
68: 69: 70:
71: public function get($key, $expire = null, $fn = null)
72: {
73: $result = $this->object->findOne(array('_id' => $this->prefix . $key), array('value', 'expire'));
74: if (null === $result || $result['expire'] < time()) {
75: $result = false;
76: } else {
77: $result = unserialize($result['value']);
78: }
79: return $this->processGetResult($key, $result, $expire, $fn);
80: }
81:
82: 83: 84:
85: public function set($key, $value, $expire = 0)
86: {
87: $result = $this->object->save(array(
88: '_id' => $this->prefix . $key,
89: 'value' => serialize($value),
90: 'expire' => $expire ? time() + $expire : 2147483647,
91: 'lastModified' => time()
92: ));
93: return $result['ok'] === 1.0;
94: }
95:
96: 97: 98:
99: public function remove($key)
100: {
101: $result = $this->object->remove(array('_id' => $this->prefix . $key));
102: return $result['n'] === 1;
103: }
104:
105: 106: 107:
108: public function exists($key)
109: {
110: $result = $this->object->findOne(array('_id' => $this->prefix . $key), array('expire'));
111: if (null === $result || $result['expire'] < time()) {
112: return false;
113: } else {
114: return true;
115: }
116: }
117:
118: 119: 120:
121: public function add($key, $value, $expire = 0)
122: {
123: if ($this->exists($key)) {
124: return false;
125: } else {
126: return $this->set($key, $value, $expire);
127: }
128: }
129:
130: 131: 132:
133: public function replace($key, $value, $expire = 0)
134: {
135: if ($this->exists($key)) {
136: return $this->set($key, $value, $expire);
137: } else {
138: return false;
139: }
140: }
141:
142: 143: 144: 145: 146:
147: public function incr($key, $offset = 1)
148: {
149: $value = $this->get($key) + $offset;
150: return $this->set($key, $value) ? $value : false;
151: }
152:
153: 154: 155:
156: public function clear()
157: {
158: return $this->object->remove();
159: }
160:
161: 162: 163: 164: 165:
166: public function getObject()
167: {
168: return $this->object;
169: }
170:
171: 172: 173: 174: 175: 176:
177: public function setObject(\MongoCollection $object)
178: {
179: $this->object = $object;
180: return $this;
181: }
182: }
183: