DoctrineMongoDBBundle Documentation

repository·5.7.x·Indexed 18 days ago

https://github.com/doctrine/doctrinemongodbbundle

A Symfony bundle that integrates the Doctrine2 MongoDB ODM into the Symfony framework. It provides configuration options for object-document mapping, including the setup of connections, document managers, metadata cache drivers, and document mapping via YAML or PHP. It supports advanced MongoDB features such as replica sets, authentication (authSource), client-side field-level encryption (CSFLE), and custom query filters.

Tokens
24.1K
Snippets
82
Records
106
Agent score
60%

What's inside DoctrineMongoDBBundle

  1. Overview of DoctrineMongoDBBundle

    5.7.x

    The DoctrineMongoDBBundle integrates the Doctrine MongoDB Object Document Mapper (ODM) into Symfony applications. It allows you to work with plain PHP objects that are transparently persisted to and from MongoDB, following a philosophy similar to the Doctrine ORM.

    Key features include:

    • Integration of Doctrine MongoDB ODM with Symfony configuration.
    • Support for common Doctrine extensions (like Sluggable or Timestampable) via integration with StofDoctrineExtensionsBundle.
  2. Install and use DoctrineMongoDBBundle

    5.7.x

    DoctrineMongoDBBundle integrates the Doctrine2 MongoDB Object Document Mapper (ODM) library into Symfony. This allows you to persist and retrieve objects to and from MongoDB within a Symfony application.

    For detailed installation and usage instructions, refer to the official Symfony documentation.

  3. Automatic Document Manager clearing with Symfony Messenger

    5.7.x
    When the symfony/messenger package is installed, DoctrineMongoDBBundle automatically registers a Messenger event subscriber. This subscriber clears all MongoDB document managers after a message is handled. This behavior ensures that each message handler operates with a fresh state, isolating handlers and preventing the accidental use of stale or out-of-date document data from previous operations.
  4. Using Doctrine Extensions with MongoDB

    5.7.x
    You can perform common tasks on your ODM entities (such as Sluggable, Timestampable, Loggable, Translatable, and Tree) by using third-party Doctrine extensions. To integrate these extensions into your Symfony application, use the StofDoctrineExtensionsBundle.
  5. Handle fixture dependencies and execution order

    5.7.x

    If one fixture depends on data created by another (e.g., a Product needing a Category), implement the Doctrine\Common\DataFixtures\DependentFixtureInterface.

    You must implement the getDependencies() method, which returns an array of class names that must be loaded before the current fixture.

    // src/DataFixtures/ProductFixtures.php
    namespace App\DataFixtures;
    
    use App\Document\Product;
    use Doctrine\Bundle\MongoDBBundle\Fixture\Fixture;
    use Doctrine\Common\DataFixtures\DependentFixtureInterface;
    use Doctrine\Persistence\ObjectManager;
    
    class ProductFixtures extends Fixture implements DependentFixtureInterface
    {
        public function load(ObjectManager $manager): void
        {
            $product = new Product();
            $product->setName('Laptop');
            $product->setPrice(999.99);
            // Retrieve reference from another fixture
            $product->setCategory($this->getReference('category-electronics'));
    
            $manager->persist($product);
            $manager->flush();
        }
    
        public function getDependencies(): array
        {
            return [CategoryFixtures::class];
        }
    }
  6. Use environment variables for MongoDB connection URIs

    5.7.x

    To support different MongoDB connection URIs across different environments, define the URI in your .env file and reference it in your doctrine_mongodb configuration using the %env()% syntax.

    1. Define the variable in .env:
    MONGODB_URI=mongodb://localhost:27017
    1. Reference it in config/packages/doctrine_mongodb.yaml:
    doctrine_mongodb:
        connections:
            default:
                server: '%env(resolve:MONGODB_URI)%'
    # .env
    MONGODB_URI=mongodb://localhost:27017
    # config/packages/doctrine_mongodb.yaml
    doctrine_mongodb:
        connections:
            default:
                server: '%env(resolve:MONGODB_URI)%'
  7. Embed a Document Form into a Wrapper Model

    5.7.x

    When a form requires extra fields that are not stored in the database (e.g., 'terms and conditions' checkbox), use a 'wrapper' or 'DTO' model. This model holds both the actual MongoDB Document and the extra fields.

    1. Create the Wrapper Model: Define a plain class that contains the Document and the extra properties.
    2. Create the Wrapper Form: In the buildForm method, add the Document form as a field. Use property_path if the extra field needs to map to a specific property in the wrapper.

    Example Wrapper Model:

    namespace App\Form\Model;
    
    use App\Document\User;
    use Symfony\Component\Validator\Constraints as Assert;
    
    class Registration
    {
        /**
         * @Assert\Type(type="App\Document\User")
         */
        protected $user;
    
        /**
         * @Assert\NotBlank()
         * @Assert\IsTrue()
         */
        protected $termsAccepted;
    
        // ... getters and setters
    }

    Example Wrapper Form:

    namespace App\Form\Type;
    
    use App\Form\Type\UserType;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
    use Symfony\Component\Form\FormBuilderInterface;
    
    class RegistrationType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('user', UserType::class);
            $builder->add('terms', CheckboxType::class, ['property_path' => 'termsAccepted']);
        }
    }
  8. Get help for a specific Doctrine MongoDB command

    5.7.x

    To see detailed information, usage instructions, and options for a specific Doctrine MongoDB command, use the help command followed by the command name. For example, to get details about the doctrine:mongodb:query command, run:

    php bin/console help doctrine:mongodb:query
  9. Register document mappings in a custom bundle

    5.7.x

    If you are developing a bundle that contains Doctrine MongoDB documents, you must register your mappings so the application's DocumentManager can recognize them.

    To simplify this, DoctrineMongoDBBundle provides the DoctrineMongoDBMappingsPass compiler pass. You should register this pass within your bundle's build() method.

    When configuring the pass, you must provide:

    1. An array of mappings where the key is the directory path to your mapping files and the value is the document namespace.
    2. A parameter name that specifies which DocumentManager should use these mappings.
    3. A parameter name (boolean) that acts as a feature flag; the mappings will only be enabled if this parameter is set to true.
    namespace Awesome\AwesomeBundle;
    
    use Doctrine\Bundle\MongoDBBundle\DependencyInjection\Compiler\DoctrineMongoDBMappingsPass;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\HttpKernel\Bundle\Bundle;
    
    class AwesomeBundle extends Bundle
    {
        public function build(ContainerBuilder $container): void
        {
            parent::build($container);
    
            // The path to your mapping files
            $mappings = [
                __DIR__.'/Resources/config/doctrine-mapping' => 'Awesome\AwesomeBundle\Model',
            ];
    
            $container->addCompilerPass(
                DoctrineMongoDBMappingsPass::createXmlMappingDriver(
                    $mappings,
                    ['awesome_bundle.model_manager_name'],
                    'awesome_bundle.backend_type_mongodb'
                )
            );
        }
    }