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 Laravel Package

api-platform/doctrine-odm

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require api-platform/doctrine-odm
    

    Ensure doctrine/doctrine-mongodb-odm-bundle and api-platform/core are also installed.

  2. Configuration Update config/packages/doctrine_mongodb_odm.yaml to include:

    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"
                        alias: App
    
  3. First Use Case Define a MongoDB document (e.g., src/Document/Book.php):

    namespace App\Document;
    
    use ApiPlatform\Core\Annotation\ApiResource;
    use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
    
    #[ApiResource]
    #[MongoDB\Document(collection: "books")]
    class Book
    {
        #[MongoDB\Id]
        private ?string $id = null;
    
        #[MongoDB\Field(type: "string")]
        public string $title;
    
        #[MongoDB\Field(type: "string")]
        public string $author;
    }
    

    Run migrations:

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

Implementation Patterns

Workflows

  1. CRUD Operations Leverage API Platform’s built-in controllers for RESTful endpoints:

    php bin/console make:entity --entity=Book --no-interaction
    

    Use @ApiResource annotations to auto-generate endpoints (e.g., /api/books).

  2. Data Transformation Customize serialization/deserialization with ApiResource options:

    #[ApiResource(
        operations: [
            new Get(),
            new Post(
                normalizationContext: ['groups' => ['book:write']],
                denormalizationContext: ['groups' => ['book:write']]
            )
        ]
    )]
    
  3. Querying with Filters Use API Platform’s built-in filters (e.g., SearchFilter, DateFilter) or create custom ones:

    use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
    
    #[ApiResource(
        filters: [new SearchFilter(fields: ['title^', 'author^'])]
    )]
    
  4. MongoDB-Specific Features

    • Aggregation Pipelines: Use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator for custom queries.
    • References: Define relationships with @MongoDB\ReferenceOne/@MongoDB\ReferenceMany.
  5. Event Subscribers Hook into lifecycle events (e.g., prePersist, postRemove) via API Platform’s event system:

    use ApiPlatform\Core\EventListener;
    use Symfony\Component\HttpKernel\Event\ViewEvent;
    
    class BookSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                KernelEvents::VIEW => ['onView', 10],
            ];
        }
    
        public function onView(ViewEvent $event)
        {
            $book = $event->getControllerResult();
            if ($book instanceof Book) {
                $book->setUpdatedAt(new \DateTime());
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Schema Migrations

    • Issue: Running doctrine:mongodb:schema:update without --force may fail if the schema is out of sync.
    • Fix: Use --force cautiously in development; avoid in production. Prefer manual schema updates.
  2. Idempotency

    • Issue: MongoDB’s _id is auto-generated but may conflict with API Platform’s id field if not handled.
    • Fix: Explicitly define @MongoDB\Id and ensure it’s not overridden in ApiResource.
  3. Circular References

    • Issue: Serialization fails with circular references (e.g., AuthorBook).
    • Fix: Use #[Groups] or #[SerializedName] to control which fields are exposed.
  4. Pagination

    • Issue: Default pagination may not work as expected with MongoDB’s cursor-based queries.
    • Fix: Configure ApiPlatform\Core\Bridge\Doctrine\Orm\Pagination\MongoDbPagination in config/packages/api_platform.yaml:
      api_platform:
          pagination:
              enabled: true
              client_enabled: true
              items_per_page: 30
      
  5. Transaction Handling

    • Issue: MongoDB ODM doesn’t support transactions natively (unlike Doctrine ORM).
    • Fix: Use doctrine_mongodb_odm.event_listeners.transaction or implement compensating transactions.

Tips

  1. Debugging Queries Enable MongoDB logging in config/packages/monolog.yaml:

    handlers:
        mongodb:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.mongodb.log"
            level: debug
            channels: ["doctrine"]
    
  2. Testing Use mongodb:drop-db and mongodb:create-db in phpunit.xml.dist:

    <env name="MONGODB_URL" value="mongodb://localhost:27017/test_db"/>
    

    Run tests with:

    php bin/console doctrine:mongodb:drop-db --force
    php bin/console doctrine:mongodb:create-db
    
  3. Performance

    • Indexing: Add @MongoDB\Index annotations to critical fields (e.g., title).
    • Projection: Use hydrationMode: "CUSTOM" in ApiResource to fetch only required fields.
  4. Hybrid Projects For projects using both SQL and MongoDB:

    • Use doctrine/doctrine-bundle and doctrine-mongodb-odm-bundle side-by-side.
    • Configure api_platform to route entities to the correct data provider:
      api_platform:
          formats:
              jsonld: ['application/ld+json']
              json: ['application/json']
              html: ['text/html']
          patch_formats:
              json: ['application/merge-patch+json']
              jsonapi: ['application/vnd.api+json']
      
  5. Extensions

    • Custom Actions: Add operations dynamically:
      use ApiPlatform\Core\Annotation\ApiProperty;
      
      #[ApiResource(
          operations: [
              new GetCollection(),
              new Post(),
              new ApiPlatform\Core\Annotation\ApiResource\Get(
                  uriTemplate: '/books/{id}/reviews',
                  requirements: ['id' => '\w+'],
                  normalizationContext: ['groups' => ['review:read']]
              )
          ]
      )]
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky