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

Ddd Generator Bundle Laravel Package

becklyn/ddd-generator-bundle

Symfony bundle to generate DDD boilerplate via Maker commands. Installs as a dev dependency and provides abstract makers (DddMaker, entity/test/command variants) plus templating support so you can create and register custom generators.

View on GitHub
Deep Wiki
Context7

Getting Started

To begin leveraging becklyn/ddd-generator-bundle in a Laravel project, follow these minimal steps:

  1. Install the Bundle Run this command in your Laravel project directory:

    composer require becklyn/ddd-generator-bundle --dev
    
  2. Enable the Bundle Add the bundle to config/bundles.php:

    return [
        // ...
        Becklyn\DddGeneratorBundle\BecklynDddGeneratorBundle::class => ['dev' => true],
    ];
    
  3. Generate Your First Entity Use the make:ddd-entity command to scaffold a basic DDD entity:

    php artisan make:ddd-entity User
    
    • Select the domain (e.g., UserManagement) when prompted.
    • The command generates:
      • Entity class (src/Domain/UserManagement/Entity/User.php)
      • Entity repository interface (src/Domain/UserManagement/Repository/UserRepositoryInterface.php)
      • Test classes (e.g., tests/Domain/UserManagement/Entity/UserTest.php)
  4. Verify Output Check the generated files for:

    • Proper namespace usage (e.g., \App\Domain\UserManagement\Entity\User).
    • Basic DDD patterns (e.g., id, createdAt, updatedAt properties).
    • Test traits (e.g., EntityTestTrait).

First Use Case: Generate a command and handler for a domain action (e.g., user registration):

php artisan make:ddd-command RegisterUser
  • Select the domain (e.g., UserManagement).
  • The command generates:
    • Command class (src/Domain/UserManagement/Command/RegisterUser.php)
    • Command handler (src/Domain/UserManagement/Command/Handler/RegisterUserHandler.php)
    • Test class (tests/Domain/UserManagement/Command/Handler/RegisterUserHandlerTest.php).
  • Immediate Value: Jumpstart CRUD operations or domain-specific workflows without manual boilerplate.

Implementation Patterns

1. Domain Layer Scaffolding

Workflow: Use the bundle to generate the core domain layer (entities, repositories, commands) in a structured way:

# Generate an entity with repository
php artisan make:ddd-entity Product --repository

# Generate a command with handler
php artisan make:ddd-command UpdateProductPrice

Integration Tips:

  • Namespace Organization: Align generated namespaces with your project’s domain structure (e.g., \App\Domain\Ecommerce\Entity\Product).
  • Repository Patterns: Extend DoctrineRepository or EloquentRepository (if using ORMs) to implement the generated interfaces.
  • Event Sourcing: Pair with becklyn/ddd-event-bundle to generate domain events alongside entities:
    php artisan make:ddd-event ProductCreated
    

2. Test-Driven Development (TDD)

Workflow: Generate test classes first, then implement the entity/command:

# Generate tests for an entity
php artisan make:ddd-entity User --test-only

# Implement the entity based on test expectations
php artisan make:ddd-entity User

Patterns:

  • Test Traits: Leverage built-in traits like EntityTestTrait for common assertions (e.g., assertEntityIsCreated()).
  • Mock Repositories: Use the generated repository interfaces to mock dependencies in tests:
    $repository = $this->createMock(ProductRepositoryInterface::class);
    $repository->method('find')->willReturn($product);
    $this->entity->setRepository($repository);
    
  • Command Tests: The generated CommandHandlerTestTrait provides fixtures for testing command execution:
    public function testExecute_createsProduct(): void
    {
        $this->givenEntityIsCreated(Product::class);
        $this->assertCommandExecutesSuccessfully(new UpdateProductPrice(...));
    }
    

3. Custom Generators

Workflow: Extend the bundle to create domain-specific generators (e.g., for value objects or aggregates):

// src/Maker/CustomValueObjectMaker.php
namespace App\Maker;

use Becklyn\DddGeneratorBundle\Maker\DddMaker;

class CustomValueObjectMaker extends DddMaker
{
    protected function getTemplatePath(): string
    {
        return __DIR__.'/../../Resources/skeleton/ddd/value_object.tpl.php';
    }

    protected function getExtraVariables(): array
    {
        return array_merge(parent::getExtraVariables(), [
            'value_object_namespace' => $this->getNamespace().'\ValueObject',
        ]);
    }
}

Register the Maker:

# config/services.yaml
services:
    App\Maker\CustomValueObjectMaker:
        tags:
            - { name: maker.command, command: 'make:ddd-value-object' }

Usage:

php artisan make:ddd-value-object EmailAddress

Tips:

  • Reuse existing templates (e.g., entity.tpl.php) as a starting point.
  • Override getDefaultNamespace() to enforce domain-specific paths.

4. CI/CD Integration

Pattern: Automate DDD layer generation in CI/CD pipelines for consistent scaffolding:

# .github/workflows/ddd-scaffold.yml
jobs:
  scaffold:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-php@v2
        with:
          php-version: '8.1'
      - run: composer install --dev
      - run: |
          php artisan make:ddd-entity User --repository
          php artisan make:ddd-command RegisterUser
      - run: git add .
      - run: git commit -m "chore: scaffold DDD layers"

Use Case: Ensure all developers start with a standardized domain layer before feature development.

5. Laravel-Specific Adaptations

Patterns:

  • Service Container Binding: Bind generated repositories to Laravel’s container:
    // app/Providers/AppServiceProvider.php
    public function register(): void
    {
        $this->app->bind(
            ProductRepositoryInterface::class,
            ProductRepository::class
        );
    }
    
  • Artisan Command Aliases: Create shortcuts for frequent commands:
    // config/console.php
    'commands' => [
        'make:ddd-entity' => 'make:entity',
        'make:ddd-command' => 'make:cmd',
    ];
    
  • IDE Support: Use PHPStorm’s "Generate" templates to integrate with the bundle’s output (e.g., auto-import generated classes).

Gotchas and Tips

Pitfalls

  1. Namespace Collisions

    • Issue: Generated classes may conflict with existing namespaces if domains share names (e.g., User in Auth and UserManagement).
    • Fix: Use multi-level domains (e.g., \App\Domain\Auth\User, \App\Domain\UserManagement\User).
    • Debug: Run composer dump-autoload if autoloading fails.
  2. Template Overrides

    • Issue: Custom templates in src/Resources/skeleton/ddd/ may not override bundle defaults.
    • Fix: Clear the cache after adding new templates:
      php artisan cache:clear
      php artisan config:clear
      
  3. PHP 8.0+ Requirements

    • Issue: The bundle requires PHP 8.0+ (since v2.0.0). Older projects may fail.
    • Fix: Update php.ini or use a .php-version file in the project root.
  4. Git Ignore Conflicts

    • Issue: Generated files may be committed accidentally.
    • Fix: Add these to .gitignore:
      /src/Domain/**/*Test.php
      /tests/Domain/**/*
      
  5. Command Prompt Hangs

    • Issue: The domain selection prompt may freeze in non-interactive environments (e.g., CI).
    • Fix: Use --domain=UserManagement to bypass the prompt:
      php artisan make:ddd-entity User --domain=UserManagement
      

Debugging Tips

  1. Verbose Output Enable debug mode for generator commands:

    php artisan make:ddd-entity User -v
    
    • Look for errors in the template rendering step.
  2. Template Debugging

    • Add <?php dump($this); die; ?> to templates to inspect variables.
    • Check var/dump/ for generated files during development.
  3. Service Registration

    • Verify your custom maker is registered by running:
      php artisan debug:makers
      

Extension Points

  1. Customizing Generated Code
    • Override templates in src/Resources/skeleton/ddd/ (e.g., entity.tpl.php).
    • Example: Add soft deletes to entities by modifying the template:
      <?php if ($extra['soft_deletes'] ?? false): ?>
      /**
       * @var \DateTime|null
       */
      protected ?\DateTimeInterface $deletedAt = null;
      <?php endif;
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor