4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
15 * MongoDB session handler.
17 * @author Markus Bachmann <markus.bachmann@bachi.biz>
19 class MongoDbSessionHandler implements \SessionHandlerInterface
22 * @var \Mongo|\MongoClient|\MongoDB\Client
27 * @var \MongoCollection
39 * List of available options:
40 * * database: The name of the database [required]
41 * * collection: The name of the collection [required]
42 * * id_field: The field name for storing the session id [default: _id]
43 * * data_field: The field name for storing the session data [default: data]
44 * * time_field: The field name for storing the timestamp [default: time]
45 * * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]
47 * It is strongly recommended to put an index on the `expiry_field` for
48 * garbage-collection. Alternatively it's possible to automatically expire
49 * the sessions in the database as described below:
51 * A TTL collections can be used on MongoDB 2.2+ to cleanup expired sessions
52 * automatically. Such an index can for example look like this:
54 * db.<session-collection>.ensureIndex(
55 * { "<expiry-field>": 1 },
56 * { "expireAfterSeconds": 0 }
59 * More details on: http://docs.mongodb.org/manual/tutorial/expire-data/
61 * If you use such an index, you can drop `gc_probability` to 0 since
62 * no garbage-collection is required.
64 * @param \Mongo|\MongoClient|\MongoDB\Client $mongo A MongoDB\Client, MongoClient or Mongo instance
65 * @param array $options An associative array of field options
67 * @throws \InvalidArgumentException When MongoClient or Mongo instance not provided
68 * @throws \InvalidArgumentException When "database" or "collection" not provided
70 public function __construct($mongo, array $options)
72 if (!($mongo instanceof \MongoDB\Client || $mongo instanceof \MongoClient || $mongo instanceof \Mongo)) {
73 throw new \InvalidArgumentException('MongoClient or Mongo instance required');
76 if (!isset($options['database']) || !isset($options['collection'])) {
77 throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler');
80 $this->mongo = $mongo;
82 $this->options = array_merge(array(
84 'data_field' => 'data',
85 'time_field' => 'time',
86 'expiry_field' => 'expires_at',
93 public function open($savePath, $sessionName)
101 public function close()
109 public function destroy($sessionId)
111 $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
113 $this->getCollection()->$methodName(array(
114 $this->options['id_field'] => $sessionId,
123 public function gc($maxlifetime)
125 $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
127 $this->getCollection()->$methodName(array(
128 $this->options['expiry_field'] => array('$lt' => $this->createDateTime()),
137 public function write($sessionId, $data)
139 $expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime'));
142 $this->options['time_field'] => $this->createDateTime(),
143 $this->options['expiry_field'] => $expiry,
146 $options = array('upsert' => true);
148 if ($this->mongo instanceof \MongoDB\Client) {
149 $fields[$this->options['data_field']] = new \MongoDB\BSON\Binary($data, \MongoDB\BSON\Binary::TYPE_OLD_BINARY);
151 $fields[$this->options['data_field']] = new \MongoBinData($data, \MongoBinData::BYTE_ARRAY);
152 $options['multiple'] = false;
155 $methodName = $this->mongo instanceof \MongoDB\Client ? 'updateOne' : 'update';
157 $this->getCollection()->$methodName(
158 array($this->options['id_field'] => $sessionId),
159 array('$set' => $fields),
169 public function read($sessionId)
171 $dbData = $this->getCollection()->findOne(array(
172 $this->options['id_field'] => $sessionId,
173 $this->options['expiry_field'] => array('$gte' => $this->createDateTime()),
176 if (null === $dbData) {
180 if ($dbData[$this->options['data_field']] instanceof \MongoDB\BSON\Binary) {
181 return $dbData[$this->options['data_field']]->getData();
184 return $dbData[$this->options['data_field']]->bin;
188 * Return a "MongoCollection" instance.
190 * @return \MongoCollection
192 private function getCollection()
194 if (null === $this->collection) {
195 $this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
198 return $this->collection;
202 * Return a Mongo instance.
204 * @return \Mongo|\MongoClient|\MongoDB\Client
206 protected function getMongo()
212 * Create a date object using the class appropriate for the current mongo connection.
214 * Return an instance of a MongoDate or \MongoDB\BSON\UTCDateTime
216 * @param int $seconds An integer representing UTC seconds since Jan 1 1970. Defaults to now.
218 * @return \MongoDate|\MongoDB\BSON\UTCDateTime
220 private function createDateTime($seconds = null)
222 if (null === $seconds) {
226 if ($this->mongo instanceof \MongoDB\Client) {
227 return new \MongoDB\BSON\UTCDateTime($seconds * 1000);
230 return new \MongoDate($seconds);