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

Symfony Mongo Maker Bundle Laravel Package

ama/symfony-mongo-maker-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation Add the bundle to your Symfony project via Composer:

    composer require ama/symfony-mongo-maker-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        AlexandraMasvidal\SymfonyMongoMakerBundle\SymfonyMongoMakerBundle::class => ['all' => true],
    ];
    
  2. Basic Command Usage Generate a MongoDB document, DTO, and CRUD controller with NelmioApiDoc annotations in one command:

    php bin/console make:mongodb-document User
    

    This creates:

    • A MongoDB document class (src/Document/User.php)
    • A DTO class (src/DTO/UserDTO.php)
    • A CRUD controller (src/Controller/UserController.php)
    • NelmioApiDoc annotations for API documentation
  3. First Use Case Use the generated controller to handle CRUD operations for User documents. The bundle auto-generates routes like:

    • GET /api/users (List users)
    • POST /api/users (Create user)
    • GET /api/users/{id} (Get user)
    • PUT/PATCH /api/users/{id} (Update user)
    • DELETE /api/users/{id} (Delete user)

    The DTO ensures type safety and validation for API requests.


Implementation Patterns

Workflows

  1. Document-Centric Development

    • Start by generating a document class for your MongoDB collections:
      php bin/console make:mongodb-document Post --fields="title:string,content:text,author:string,createdAt:datetime"
      
    • The command auto-generates:
      • MongoDB schema (e.g., @MongoDB\Document, @MongoDB\Field).
      • Getters/setters for fields.
      • Type hints for IDE autocompletion.
  2. DTO-Driven API Design

    • Use the generated DTOs to enforce request/response contracts:
      // Example: Validating a request in a controller
      public function create(Request $request, UserDTO $userDTO): Response
      {
          $user = new User();
          $userDTO->hydrate($user); // Auto-maps DTO to document
          $em->persist($user);
          $em->flush();
          return new JsonResponse($userDTO->toArray(), 201);
      }
      
    • Customize DTOs by extending the base class or overriding methods like hydrate() or toArray().
  3. CRUD Controller Integration

    • Leverage the auto-generated controller for standard operations:
      // src/Controller/UserController.php (auto-generated)
      #[Route('/users', name: 'api_user_', methods: ['GET'])]
      public function list(UserRepository $repository): Response
      {
          $users = $repository->findAll();
          return $this->json($users);
      }
      
    • Extend the controller to add business logic:
      public function create(Request $request, UserDTO $userDTO): Response
      {
          $this->validateCustomRules($userDTO);
          // ... rest of the logic
      }
      
  4. NelmioApiDoc Integration

    • The bundle auto-generates OpenAPI annotations for API documentation:
      #[Nelmio\ApiDoc\Annotation\ApiResource(
          collectionOperations: ['get', 'post'],
          itemOperations: ['get', 'put', 'delete']
      )]
      class UserController
      
    • Customize documentation by adding @ApiProperty or @ApiParam annotations to DTOs or controllers.
  5. Repository Pattern

    • Use the auto-generated repository to interact with MongoDB:
      $user = $repository->findBy(['email' => 'user@example.com']);
      $users = $repository->findBy([], ['createdAt' => -1]); // Sort by desc
      

Integration Tips

  • MongoDB Collections: Ensure your MongoDBConnection is properly configured in config/packages/mongodb.yaml.
  • Validation: Extend DTOs to add custom validation constraints (e.g., Symfony’s Assert annotations).
  • Events: Attach listeners to document lifecycle events (e.g., prePersist, preRemove) via the repository.
  • Testing: Mock the repository or use a test database for unit/integration tests:
    $this->container->get('doctrine_mongodb.odm.default_document_manager')->clear();
    
  • Custom Fields: For complex types (e.g., arrays, embedded documents), use MongoDB’s @MongoDB\EmbedOne, @MongoDB\EmbedMany, or @MongoDB\ReferenceOne.

Gotchas and Tips

Pitfalls

  1. Field Naming Conflicts

    • Avoid reserved keywords (e.g., class, type) as field names. The bundle may throw errors during generation.
    • Fix: Use underscores or rename fields manually after generation.
  2. DTO Hydration Issues

    • If a document field is named differently than the DTO property, hydration fails silently.
    • Fix: Override the hydrate() method in the DTO or use @Assert\Expression to map fields:
      #[Assert\Expression(
          expression: "this.getTitle() === null ? false : true",
          message: "Title cannot be empty."
      )]
      
  3. NelmioApiDoc Conflicts

    • If NelmioApiDoc is not installed, the bundle may generate invalid annotations.
    • Fix: Install the bundle first:
      composer require nelmio/api-doc-bundle
      
  4. MongoDB Indexes

    • The bundle does not auto-generate indexes. Add them manually in the document class:
      #[MongoDB\Index(name: "email_unique", keys: ["email" => "unique"])]
      
  5. Circular References

    • Embedded documents or references with circular dependencies (e.g., User references Post, Post references User) may cause serialization issues.
    • Fix: Use @MongoDB\Populate or customize toArray() in DTOs to avoid infinite loops.
  6. Command Overrides

    • If you’ve customized the bundle’s templates, regenerate commands may overwrite your changes.
    • Fix: Copy the template files from vendor/alexandramasvidal/symfony-mongo-maker-bundle/Resources/skeleton/ to your project’s custom path and configure the bundle to use them:
      # config/packages/symfony_mongo_maker.yaml
      alexandramasvidal_symfony_mongo_maker:
          templates_dir: '%kernel.project_dir%/custom-templates/'
      

Debugging Tips

  1. Check Generated Code

    • After running a command, inspect the generated files for errors (e.g., syntax, typos in field names).
  2. Enable Debug Mode

    • Run Symfony in debug mode to catch errors early:
      APP_ENV=dev APP_DEBUG=1 php bin/console make:mongodb-document User
      
  3. Log MongoDB Queries

    • Enable MongoDB logging in config/packages/mongodb.yaml:
      doctrine_mongodb:
          connections:
              default:
                  logging: true
                  logging_level: DEBUG
      
  4. Validate DTOs

    • Use Symfony’s validator component to validate DTOs before hydration:
      $errors = $validator->validate($userDTO);
      if (count($errors) > 0) {
          throw new ValidationException($errors);
      }
      
  5. Test Incrementally

    • Test one operation at a time (e.g., POST before GET) to isolate issues.

Extension Points

  1. Custom Templates

    • Override the default templates by creating a custom-templates directory and configuring the bundle to use it (see "Pitfalls" above).
  2. Event Subscribers

    • Attach subscribers to document events (e.g., prePersist) to add logic like:
      • Auto-generating UUIDs.
      • Setting default values.
      • Logging changes.
    • Example:
      // src/EventSubscriber/UserSubscriber.php
      use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
      
      class UserSubscriber implements EventSubscriber
      {
          public function getSubscribedEvents()
          {
              return ['prePersist'];
          }
      
          public function prePersist(LifecycleEventArgs $args)
          {
              $document = $args->getDocument();
              if ($document instanceof User) {
                  $document->setCreatedAt(new \DateTime());
              }
          }
      }
      
  3. Custom Commands

    • Extend the bundle’s commands to add custom logic (e.g., generate documents with default fields):
      php bin/console make:mongodb-document Post --default-fields="author:User,status:PostStatus"
      
  4. DTO Transformers

    • Create custom transformers to convert between documents and DTOs:
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