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

Doctrine Odm Mongodb Bridge Bundle Laravel Package

bengor-user/doctrine-odm-mongodb-bridge-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies:

    composer require bengor-user/doctrine-odm-mongodb-bridge-bundle
    composer require doctrine/mongodb-odm-bundle
    composer require friendsofsymfony/user-bundle
    

    Ensure doctrine/mongodb-odm-bundle and friendsofsymfony/user-bundle are also installed, as this bridge depends on them.

  2. Enable Bundles in config/bundles.php:

    return [
        // ...
        Doctrine\ODM\MongoDBBundle\DoctrineMongoDBBundle::class => ['all' => true],
        FriendsOfSymfony\UserBundle\FriendsOfSymfonyUserBundle::class => ['all' => true],
        BenGorUser\DoctrineODMMongoDBBridgeBundle\DoctrineODMMongoDBBridgeBundle::class => ['all' => true],
    ];
    
  3. Configure MongoDB ODM in config/packages/doctrine_mongodb_odm.yaml:

    doctrine_mongodb:
        connections:
            default:
                server: "%env(MONGODB_URL)%"
                options: {}
        document_managers:
            default:
                auto_mapping: true
                mappings:
                    App:
                        is_bundle: false
                        dir: "%kernel.project_dir%/src/Document"
                        prefix: "App\Document"
    
  4. Extend User Document: Create a User document in src/Document/User.php:

    namespace App\Document;
    
    use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
    use FriendsOfSymfony\UserBundle\Model\User as BaseUser;
    
    /**
     * @ODM\Document(collection="users")
     */
    class User extends BaseUser
    {
        // Custom fields or overrides
    }
    
  5. Update UserBundle Configuration in config/packages/fos_user.yaml:

    fos_user:
        db_driver: odm_mongodb
        firewall_name: main
        user_class: App\Document\User
    
  6. Run Migrations:

    php bin/console doctrine:mongodb:schema:update --force
    

First Use Case

Use the bundle to authenticate a user via MongoDB:

// In a controller or service
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use App\Document\User;

// Load user from MongoDB
$user = $entityManager->getRepository(User::class)->findOneBy(['username' => 'test']);

// Create token and authenticate
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);

Implementation Patterns

Workflows

  1. User Management:

    • Create User:
      $user = new User();
      $user->setUsername('john_doe');
      $user->setEmail('john@example.com');
      $user->setPlainPassword('secure123');
      $entityManager->persist($user);
      $entityManager->flush();
      
    • Update User:
      $user = $entityManager->getRepository(User::class)->find($id);
      $user->setEmail('new_email@example.com');
      $entityManager->flush();
      
  2. Authentication:

    • Use Symfony’s security system with MongoDB-backed users:
      # config/packages/security.yaml
      security:
          providers:
              fos_userbundle:
                  id: fos_user.user_provider.odm_mongodb
          firewalls:
              main:
                  pattern: ^/
                  form_login:
                      provider: fos_userbundle
                      csrf_token_generator: security.csrf.token_manager
      
  3. Role Management:

    • Assign roles dynamically:
      $user->addRole('ROLE_ADMIN');
      $entityManager->flush();
      
  4. Custom User Fields:

    • Extend User document with custom fields (e.g., profilePicture):
      /**
       * @ODM\Field(type="string")
       */
      private $profilePicture;
      

Integration Tips

  • Event Listeners: Use Symfony events to react to user lifecycle (e.g., post-persist):

    // src/EventListener/UserListener.php
    namespace App\EventListener;
    
    use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
    use Symfony\Component\HttpKernel\KernelEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class UserListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                LifecycleEventArgs::POST_PERSIST => 'onUserPersist',
            ];
        }
    
        public function onUserPersist(LifecycleEventArgs $args)
        {
            $user = $args->getDocument();
            if ($user instanceof User) {
                $user->setLastLogin(new \DateTime());
            }
        }
    }
    
  • Doctrine Extensions: Integrate with DoctrineExtensions for behaviors like timestamps:

    # config/packages/doctrine_mongodb_odm.yaml
    doctrine_mongodb:
        document_managers:
            default:
                mappings:
                    App:
                        type: annotation
                        prefix: App\Document
                        extensions:
                            - Gedmo\Timestampable\TimestampableListener
    
  • API Integration: Use Symfony’s serializers to expose user data:

    // src/Serializer/UserNormalizer.php
    namespace App\Serializer;
    
    use App\Document\User;
    use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
    
    class UserNormalizer implements NormalizerInterface
    {
        public function normalize($object, $format = null, array $context = [])
        {
            return [
                'id' => $object->getId(),
                'username' => $object->getUsername(),
                'email' => $object->getEmail(),
                'roles' => $object->getRoles(),
            ];
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Outdated Dependencies:

    • The bundle was last updated in 2017 and may not support newer Symfony (5.x+) or Doctrine ODM versions.
    • Workaround: Fork the repository and update dependencies manually or use a compatible alternative like stofl/user-bundle with MongoDB ODM.
  2. Missing Documentation:

    • The README refers to external documentation for UserBundle, which may not cover MongoDB-specific quirks.
    • Tip: Cross-reference Doctrine ODM documentation for MongoDB-specific behaviors (e.g., _id fields, embedded documents).
  3. Schema Migrations:

    • MongoDB ODM does not support traditional "migrations" like SQL. Changes to documents require manual schema updates or tools like doctrine/mongodb-odm-migrations.
    • Tip: Use --force cautiously in development:
      php bin/console doctrine:mongodb:schema:update --force
      
  4. Authentication Edge Cases:

    • Password hashing may behave differently with MongoDB. Ensure UserManager is configured correctly:
      fos_user:
          service:
              user_manager: fos_user.user_manager.odm_mongodb
      
  5. Performance with Large Datasets:

    • MongoDB queries can be slow without proper indexing. Add indexes to frequently queried fields:
      /**
       * @ODM\Index(keys={"username"="text", "email"="text"})
       */
      class User { ... }
      

Debugging

  1. Query Logging: Enable ODM query logging in config/packages/dev/doctrine_mongodb_odm.yaml:

    doctrine_mongodb:
        document_managers:
            default:
                logging: true
    
  2. Common Errors:

    • "Class not found": Ensure the user_class in fos_user.yaml matches your document’s namespace.
    • Authentication failures: Verify the security.yaml provider and firewall configurations.
    • Circular references: Use @ODM\ReferenceOne or @ODM\EmbedMany carefully to avoid infinite loops.
  3. Testing:

    • Use MongoDB\Client in tests to mock the database:
      // tests/Functional/UserTest.php
      public function testUserCreation()
      {
          $client = new MongoDB\Client('mongodb://localhost:27017');
          $db = $client->test;
          $collection = $db->users;
          $collection->insertOne([
              'username' => 'test',
              'email' => 'test@example.com',
              'password' => '$2y$13$...', // Pre-hashed password
          ]);
      }
      

Extension Points

  1. Custom User Providers: Extend the default provider for custom logic:
    // src/Security/UserProvider
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope