Installation Add the bundle via Composer:
composer require e-butik/mongo-session-bundle
Register the bundle in config/bundles.php:
return [
// ...
Ebutik\MongoSessionBundle\EbutikMongoSessionBundle::class => ['all' => true],
];
Configuration
Configure MongoDB connection in config/packages/ebutik_mongo_session.yaml:
ebutik_mongo_session:
client: mongodb://localhost:27017
database: session_db
collection: sessions
ttl: 3600 # Session TTL in seconds (optional)
First Use Case
Enable the session handler in config/packages/framework.yaml:
framework:
session:
handler_id: ebutik_mongo_session.session.handler
Test by creating a session in a controller:
use Symfony\Component\HttpFoundation\Session\SessionInterface;
public function testSession(SessionInterface $session)
{
$session->set('test_key', 'test_value');
return new Response('Session stored in MongoDB!');
}
Session Management Use the bundle’s handler for standard Symfony session operations:
// Start session
$session->start();
// Store/retrieve data
$session->set('user_id', $user->getId());
$userId = $session->get('user_id');
// Flash messages
$session->getFlashBag()->add('success', 'Operation completed!');
Custom Session Data Handling Extend the default behavior by overriding the handler:
# config/packages/ebutik_mongo_session.yaml
ebutik_mongo_session:
handler_id: app.custom_mongo_session_handler
Define a custom handler in src/Session/CustomMongoHandler.php:
use Ebutik\MongoSessionBundle\Session\MongoHandler;
class CustomMongoHandler extends MongoHandler
{
public function saveSession($session)
{
// Custom logic (e.g., encryption, logging)
parent::saveSession($session);
}
}
TTL-Based Session Expiry Leverage MongoDB’s TTL index for automatic session cleanup:
ebutik_mongo_session:
ttl: 86400 # 24 hours
Ensure the sessions collection has a TTL index:
db.sessions.createIndex({ "expiresAt": 1 }, { expireAfterSeconds: 86400 })
Multi-Environment Config Use Symfony’s parameter bag for environment-specific settings:
# config/packages/dev/ebutik_mongo_session.yaml
ebutik_mongo_session:
client: '%env(MONGO_DEV_URL)%'
ttl: 1800 # Shorter TTL for dev
MongoDB Connection Issues
ConnectionException.php bin/console debug:container ebutik_mongo_session.client to inspect the connection.config/packages/monolog.yaml to log connection errors:
monolog:
handlers:
mongo:
type: stream
path: "%kernel.logs_dir%/mongo.log"
level: error
Session Data Corruption
serialize()/unserialize() for complex objects:
$session->set('user', serialize($user));
$user = unserialize($session->get('user'));
TTL Index Not Applied
db.sessions.createIndex({ "expiresAt": 1 }, { expireAfterSeconds: 3600 })
ebutik_mongo_session:create-ttl-index command (if available) or a migration script.Concurrent Session Writes
$sessionData = $this->getSessionData($sessionId);
$sessionData['data'] = $newData;
$this->updateSession($sessionId, $sessionData, ['expiresAt' => new \MongoDB\BSON\UTCDateTime()]);
Inspect Session Data Use MongoDB Compass or the CLI to verify session documents:
db.sessions.find().pretty()
Enable Query Logging Configure the MongoDB client to log queries:
ebutik_mongo_session:
client_options:
logger: true
Test Session Lifecycle Simulate session expiry with:
$session->setExpiration(0); // Expire immediately
Custom Session Storage
Override Ebutik\MongoSessionBundle\Session\MongoHandler to implement:
openssl_encrypt).gzcompress).Event Listeners
Subscribe to session events (e.g., kernel.request, kernel.response) to:
// src/EventListener/SessionListener.php
use Symfony\Component\HttpKernel\Event\RequestEvent;
class SessionListener
{
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$session = $event->getRequest()->getSession();
// Custom logic (e.g., session validation)
}
}
Async Session Cleanup Use Symfony Messenger to asynchronously purge expired sessions:
// src/Message/DeleteExpiredSessions.php
class DeleteExpiredSessions implements MessageInterface {}
// src/MessageHandler/DeleteExpiredSessionsHandler.php
use Ebutik\MongoSessionBundle\Session\MongoHandler;
class DeleteExpiredSessionsHandler
{
public function __invoke(DeleteExpiredSessions $message)
{
$handler = new MongoHandler();
$handler->gc(3600); // Delete sessions older than 1 hour
}
}
How can I help you explore Laravel packages today?