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 * Session handler using the mongodb/mongodb package and MongoDB driver extension.
17 * @author Markus Bachmann <markus.bachmann@bachi.biz>
19 * @see https://packagist.org/packages/mongodb/mongodb
20 * @see http://php.net/manual/en/set.mongodb.php
22 class MongoDbSessionHandler extends AbstractSessionHandler
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 \MongoDB\Client $mongo A MongoDB\Client 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 \MongoClient || $mongo instanceof \Mongo) {
73 @trigger_error(sprintf('Using %s with the legacy mongo extension is deprecated as of 3.4 and will be removed in 4.0. Use it with the mongodb/mongodb package and ext-mongodb instead.', __CLASS__), E_USER_DEPRECATED);
76 if (!($mongo instanceof \MongoDB\Client || $mongo instanceof \MongoClient || $mongo instanceof \Mongo)) {
77 throw new \InvalidArgumentException('MongoClient or Mongo instance required');
80 if (!isset($options['database']) || !isset($options['collection'])) {
81 throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler');
84 $this->mongo = $mongo;
86 $this->options = array_merge(array(
88 'data_field' => 'data',
89 'time_field' => 'time',
90 'expiry_field' => 'expires_at',
97 public function close()
105 protected function doDestroy($sessionId)
107 $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
109 $this->getCollection()->$methodName(array(
110 $this->options['id_field'] => $sessionId,
119 public function gc($maxlifetime)
121 $methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteMany' : 'remove';
123 $this->getCollection()->$methodName(array(
124 $this->options['expiry_field'] => array('$lt' => $this->createDateTime()),
133 protected function doWrite($sessionId, $data)
135 $expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime'));
138 $this->options['time_field'] => $this->createDateTime(),
139 $this->options['expiry_field'] => $expiry,
142 $options = array('upsert' => true);
144 if ($this->mongo instanceof \MongoDB\Client) {
145 $fields[$this->options['data_field']] = new \MongoDB\BSON\Binary($data, \MongoDB\BSON\Binary::TYPE_OLD_BINARY);
147 $fields[$this->options['data_field']] = new \MongoBinData($data, \MongoBinData::BYTE_ARRAY);
148 $options['multiple'] = false;
151 $methodName = $this->mongo instanceof \MongoDB\Client ? 'updateOne' : 'update';
153 $this->getCollection()->$methodName(
154 array($this->options['id_field'] => $sessionId),
155 array('$set' => $fields),
165 public function updateTimestamp($sessionId, $data)
167 $expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime'));
169 if ($this->mongo instanceof \MongoDB\Client) {
170 $methodName = 'updateOne';
173 $methodName = 'update';
174 $options = array('multiple' => false);
177 $this->getCollection()->$methodName(
178 array($this->options['id_field'] => $sessionId),
179 array('$set' => array(
180 $this->options['time_field'] => $this->createDateTime(),
181 $this->options['expiry_field'] => $expiry,
192 protected function doRead($sessionId)
194 $dbData = $this->getCollection()->findOne(array(
195 $this->options['id_field'] => $sessionId,
196 $this->options['expiry_field'] => array('$gte' => $this->createDateTime()),
199 if (null === $dbData) {
203 if ($dbData[$this->options['data_field']] instanceof \MongoDB\BSON\Binary) {
204 return $dbData[$this->options['data_field']]->getData();
207 return $dbData[$this->options['data_field']]->bin;
211 * Return a "MongoCollection" instance.
213 * @return \MongoCollection
215 private function getCollection()
217 if (null === $this->collection) {
218 $this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
221 return $this->collection;
225 * Return a Mongo instance.
227 * @return \Mongo|\MongoClient|\MongoDB\Client
229 protected function getMongo()
235 * Create a date object using the class appropriate for the current mongo connection.
237 * Return an instance of a MongoDate or \MongoDB\BSON\UTCDateTime
239 * @param int $seconds An integer representing UTC seconds since Jan 1 1970. Defaults to now.
241 * @return \MongoDate|\MongoDB\BSON\UTCDateTime
243 private function createDateTime($seconds = null)
245 if (null === $seconds) {
249 if ($this->mongo instanceof \MongoDB\Client) {
250 return new \MongoDB\BSON\UTCDateTime($seconds * 1000);
253 return new \MongoDate($seconds);