ama/symfony-mongo-maker-bundle
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],
];
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:
src/Document/User.php)src/DTO/UserDTO.php)src/Controller/UserController.php)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.
Document-Centric Development
php bin/console make:mongodb-document Post --fields="title:string,content:text,author:string,createdAt:datetime"
@MongoDB\Document, @MongoDB\Field).DTO-Driven API Design
// 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);
}
hydrate() or toArray().CRUD Controller Integration
// 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);
}
public function create(Request $request, UserDTO $userDTO): Response
{
$this->validateCustomRules($userDTO);
// ... rest of the logic
}
NelmioApiDoc Integration
#[Nelmio\ApiDoc\Annotation\ApiResource(
collectionOperations: ['get', 'post'],
itemOperations: ['get', 'put', 'delete']
)]
class UserController
@ApiProperty or @ApiParam annotations to DTOs or controllers.Repository Pattern
$user = $repository->findBy(['email' => 'user@example.com']);
$users = $repository->findBy([], ['createdAt' => -1]); // Sort by desc
MongoDBConnection is properly configured in config/packages/mongodb.yaml.Assert annotations).prePersist, preRemove) via the repository.$this->container->get('doctrine_mongodb.odm.default_document_manager')->clear();
@MongoDB\EmbedOne, @MongoDB\EmbedMany, or @MongoDB\ReferenceOne.Field Naming Conflicts
class, type) as field names. The bundle may throw errors during generation.DTO Hydration Issues
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."
)]
NelmioApiDoc Conflicts
composer require nelmio/api-doc-bundle
MongoDB Indexes
#[MongoDB\Index(name: "email_unique", keys: ["email" => "unique"])]
Circular References
User references Post, Post references User) may cause serialization issues.@MongoDB\Populate or customize toArray() in DTOs to avoid infinite loops.Command Overrides
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/'
Check Generated Code
Enable Debug Mode
APP_ENV=dev APP_DEBUG=1 php bin/console make:mongodb-document User
Log MongoDB Queries
config/packages/mongodb.yaml:
doctrine_mongodb:
connections:
default:
logging: true
logging_level: DEBUG
Validate DTOs
$errors = $validator->validate($userDTO);
if (count($errors) > 0) {
throw new ValidationException($errors);
}
Test Incrementally
POST before GET) to isolate issues.Custom Templates
custom-templates directory and configuring the bundle to use it (see "Pitfalls" above).Event Subscribers
prePersist) to add logic like:
// 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());
}
}
}
Custom Commands
php bin/console make:mongodb-document Post --default-fields="author:User,status:PostStatus"
DTO Transformers
How can I help you explore Laravel packages today?