Skip to content

Commit 2e7757f

Browse files
Add cookbook article for using MongoDB to store session data
1 parent ef211b3 commit 2e7757f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
How to Use MongoDbSessionHandler to Store Sessions in a MongoDB Database
2+
========================================================================
3+
4+
The default Symfony session storage writes the session information to files.
5+
Some medium to large websites use a NoSQL database called MongoDB to store the
6+
session values instead of files, because databases are easier to use and scale
7+
in a multi-webserver environment.
8+
9+
Symfony has a built-in solution for NoSQL database session storage called
10+
:class:`Symfony\\Component\\HttpFoundation\\Session\\Storage\\Handler\\MongoDbSessionHandler`.
11+
MongoDB is an open-source document database that provides high performance,
12+
high availability, and automatic scaling. This article assumes that you have
13+
already `installed and configured a MongoDB server`_. To use it, you just
14+
need to change/add some parameters in the main configuration file:
15+
16+
.. configuration-block::
17+
18+
.. code-block:: yaml
19+
20+
# app/config/config.yml
21+
framework:
22+
session:
23+
# ...
24+
handler_id: session.handler.mongo
25+
cookie_lifetime: 2592000 # optional, it is set to 30 days here
26+
gc_maxlifetime: 2592000 # optional, it is set to 30 days here
27+
28+
parameters:
29+
# ...
30+
mongo.session.options:
31+
database: session_db # your MongoDB database name
32+
collection: session # your MongoDB collection name
33+
mongodb_host: 1.2.3.4 # your MongoDB server's IP
34+
mongodb_username: my_username
35+
mongodb_password: my_password
36+
37+
services:
38+
# ...
39+
mongo_client:
40+
class: MongoClient
41+
# if using a username and password
42+
arguments: [mongodb://%mongodb_username%:%mongodb_password%@%mongodb_host%:27017]
43+
# if not using a username and password
44+
arguments: [mongodb://%mongodb_host%:27017]
45+
session.handler.mongo:
46+
class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler
47+
arguments: [@mongo_client, %mongo.session.options%]
48+
49+
Setting Up the MongoDB Collection
50+
---------------------------------
51+
Because MongoDB uses dynamic collection schemas, you do not need to do anything to initialize your
52+
session collection.
53+
54+
.. _installed and configured a MongoDB server: http://docs.mongodb.org/manual/installation/

0 commit comments

Comments
 (0)