Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mongo Session Bundle Laravel Package

e-butik/mongo-session-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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],
    ];
    
  2. 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)
    
  3. 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!');
    }
    

Implementation Patterns

Common Workflows

  1. 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!');
    
  2. 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);
        }
    }
    
  3. 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 })
    
  4. 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
    

Gotchas and Tips

Pitfalls

  1. MongoDB Connection Issues

    • Symptom: Sessions fail silently or throw ConnectionException.
    • Fix: Verify the MongoDB URI and credentials. Use php bin/console debug:container ebutik_mongo_session.client to inspect the connection.
    • Tip: Enable debug mode in config/packages/monolog.yaml to log connection errors:
      monolog:
          handlers:
              mongo:
                  type: stream
                  path: "%kernel.logs_dir%/mongo.log"
                  level: error
      
  2. Session Data Corruption

    • Symptom: Session data appears malformed or incomplete.
    • Cause: Serialization/deserialization issues (e.g., non-serializable objects).
    • Fix: Ensure session data is serializable. Use serialize()/unserialize() for complex objects:
      $session->set('user', serialize($user));
      $user = unserialize($session->get('user'));
      
  3. TTL Index Not Applied

    • Symptom: Sessions are not auto-expired.
    • Fix: Manually create the TTL index in MongoDB:
      db.sessions.createIndex({ "expiresAt": 1 }, { expireAfterSeconds: 3600 })
      
    • Tip: Use the ebutik_mongo_session:create-ttl-index command (if available) or a migration script.
  4. Concurrent Session Writes

    • Symptom: Race conditions when multiple requests update the same session.
    • Fix: Use MongoDB’s atomic operators or implement optimistic locking:
      $sessionData = $this->getSessionData($sessionId);
      $sessionData['data'] = $newData;
      $this->updateSession($sessionId, $sessionData, ['expiresAt' => new \MongoDB\BSON\UTCDateTime()]);
      

Debugging Tips

  1. Inspect Session Data Use MongoDB Compass or the CLI to verify session documents:

    db.sessions.find().pretty()
    
  2. Enable Query Logging Configure the MongoDB client to log queries:

    ebutik_mongo_session:
        client_options:
            logger: true
    
  3. Test Session Lifecycle Simulate session expiry with:

    $session->setExpiration(0); // Expire immediately
    

Extension Points

  1. Custom Session Storage Override Ebutik\MongoSessionBundle\Session\MongoHandler to implement:

    • Encryption (e.g., openssl_encrypt).
    • Compression (e.g., gzcompress).
    • Custom metadata storage.
  2. Event Listeners Subscribe to session events (e.g., kernel.request, kernel.response) to:

    • Log session activity.
    • Validate session data on startup.
    // 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)
        }
    }
    
  3. 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
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui