By default Symfony stores session data using the default handler, which uses the server filesystem.
Storing session data in files has many drawbacks and in many cases it just does not even work, with simplest example being if your app is served by multiple web servers behind a load balancer.
If you are already using MongoDB to store your application data using Doctrine ODM, it makes a lot of sense to use MongoDB as well for sessions.
The configuration is quite simple thanks to the Dependency Injection Container (DIC) and the flexible configuration of Symfony. The MongoDbSessionHandler class requires a reference to the Mongo object (the connection to MongoDB) and an array with a few entries to define which database and collection to use.
First, we need to define the session handler service in the services section of config.yml:
session.handler.mongo: class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler arguments: [@mongo, %mongo.session.options%]
Since you are already using Doctrine ODM, it is a good idea to reuse the connection for your sessions. This is easily accomplished by defining a couple of extra services in the same section where you added the previous entry:
mongo.connection: class: MongoDoctrine\MongoDB\Connection factory_service: doctrine.odm.mongodb.document_manager factory_method: getConnection calls: - [initialize, ] mongo: class: Mongo factory_service: mongo.connection factory_method: getMongo
Next, we need to define the database and collection where we will store the session data, in the parameters section of the config.yml add this:
mongo.session.options: database: app_session collection: session
And finally, tell Symfony to use the new session handler for session data:
framework: session: handler_id: session.handler.mongo
That’s it! Since MongoDB creates databases and collections on the fly, there is no need to pre-create them.