PHP code example of mghrby / modular-ddd

1. Go to this page and download the library: Download mghrby/modular-ddd library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mghrby / modular-ddd example snippets


// Modules/Sales/Application/Commands/CreateOrderCommand.php
namespace Modules\Sales\Application\Commands;

use LaravelModularDDD\CQRS\Command;

class CreateOrderCommand extends Command
{
    public function __construct(
        public readonly string $customerId,
        public readonly array $items,
        public readonly float $totalAmount
    ) {}
}

// Modules/Sales/Application/Commands/CreateOrderHandler.php
namespace Modules\Sales\Application\Commands;

use LaravelModularDDD\CQRS\CommandHandler;
use Modules\Sales\Domain\Aggregates\Order;
use Modules\Sales\Domain\Repositories\OrderRepository;

class CreateOrderHandler extends CommandHandler
{
    public function __construct(
        private OrderRepository $repository
    ) {}

    public function handle(CreateOrderCommand $command): void
    {
        $order = Order::create(
            $command->customerId,
            $command->items,
            $command->totalAmount
        );

        $this->repository->save($order);
    }
}

use LaravelModularDDD\CQRS\CommandBus;
use Modules\Sales\Application\Commands\CreateOrderCommand;

class OrderController extends Controller
{
    public function __construct(
        private CommandBus $commandBus
    ) {}

    public function store(Request $request)
    {
        $command = new CreateOrderCommand(
            customerId: $request->customer_id,
            items: $request->items,
            totalAmount: $request->total
        );

        $this->commandBus->dispatch($command);

        return response()->json(['message' => 'Order created']);
    }
}

use LaravelModularDDD\EventSourcing\EventStore;
use LaravelModularDDD\EventSourcing\SnapshotStore;

// Configure snapshot strategy
config(['modular-ddd.snapshots.strategy' => 'adaptive']);

// Load aggregate with automatic snapshot optimization
$order = $eventStore->load($orderId, Order::class);

// Events are automatically stored and snapshots created based on strategy
$order->process($payment);
$eventStore->save($order);

use LaravelModularDDD\CQRS\QueryBus;
use Modules\Sales\Application\Queries\GetOrderDetailsQuery;

// Query with automatic caching
$query = new GetOrderDetailsQuery($orderId);
$orderDetails = $queryBus->ask($query);

// Cache is automatically managed across L1, L2, and L3 tiers

use LaravelModularDDD\Modules\ModuleBus;

// Send message to another module
$moduleBus->send('Inventory', 'ReserveStock', [
    'order_id' => $orderId,
    'items' => $items
]);

// Listen for module events
$moduleBus->listen('Payment', 'PaymentCompleted', function ($event) {
    // Handle payment completion
});

return [
    'modules_path' => base_path('Modules'),

    'event_store' => [
        'connection' => env('EVENT_STORE_CONNECTION', 'mysql'),
        'table' => 'event_store',
        'chunk_size' => 1000,
    ],

    'snapshots' => [
        'enabled' => true,
        'strategy' => 'adaptive', // simple, adaptive, time_based
        'threshold' => 100,
    ],

    'cqrs' => [
        'cache' => [
            'l1_enabled' => true,
            'l2_enabled' => true,
            'l3_enabled' => true,
            'ttl' => 3600,
        ],
        'async' => [
            'enabled' => false,
            'queue' => 'default',
        ],
    ],

    'performance' => [
        'profile' => 'balanced', // startup, growth, scale, enterprise
    ],
];

use LaravelModularDDD\Testing\AggregateTestCase;
use Modules\Sales\Domain\Aggregates\Order;
use Modules\Sales\Domain\Events\OrderCreated;

class OrderTest extends AggregateTestCase
{
    public function test_order_creation()
    {
        $this->given([])
            ->when(fn() => Order::create('customer-1', ['item-1'], 100.00))
            ->then([
                new OrderCreated('customer-1', ['item-1'], 100.00)
            ]);
    }
}

// config/modular-ddd.php
'performance' => [
    'profile' => 'enterprise', // For high-load applications
]
bash
php artisan vendor:publish --provider="LaravelModularDDD\ModularDddServiceProvider"
php artisan migrate
bash
php artisan modular:make:query {module} {query}
    {--handler}             # Generate query handler
    {--no-cache}            # Skip caching implementation
    {--paginated}           # Generate paginated query
    {--dry-run}             # Preview files without creating

# Examples
php artisan modular:make:query Sales GetOrderQuery --handler
php artisan modular:make:query Inventory ListProductsQuery --paginated
php artisan modular:make:query Payment FindPaymentQuery --no-cache --dry-run
bash
php artisan modular:make:factory {module}
    {--aggregate=}   # Specific aggregate to create factory for
    {--force}        # Overwrite existing factories

# Examples
php artisan modular:make:factory Sales --aggregate=Order
php artisan modular:make:factory Inventory --force
bash
php artisan modular:info {module?}
    {--detailed}     # Show detailed component information
    {--json}         # Output in JSON format

# Examples
php artisan modular:info Sales --detailed
php artisan modular:info --json
bash
php artisan modular:list
    {--enabled}      # Show only enabled modules
    {--disabled}     # Show only disabled modules
    {--json}         # Output in JSON format

# Examples
php artisan modular:list --enabled
php artisan modular:list --json
bash
php artisan modular:health
    {--module=}      # Check specific module
    {--detailed}     # Show detailed health information
    {--fix}          # Attempt to fix common issues

# Examples
php artisan modular:health --module=Sales --detailed
php artisan modular:health --fix
bash
php artisan modular:enable {modules*}
    {--force}        # Force enable even if dependencies are missing

php artisan modular:disable {modules*}
    {--with-dependents}  # Also disable modules that depend on these
    {--force}            # Force disable even if other modules depend on them
    {--dry-run}          # Show what would be disabled without making changes

# Examples
php artisan modular:enable Sales Inventory
php artisan modular:disable Payment --with-dependents
php artisan modular:disable Sales --dry-run
bash
php artisan modular:migrate {module?}
    {--force}        # Force migration in production
    {--path=}        # Specific migration path
    {--pretend}      # Show SQL that would be executed

# Examples
php artisan modular:migrate Sales
php artisan modular:migrate --force
bash
php artisan modular:migrate:rollback {module?}
    {--step=}        # Number of migrations to rollback
    {--force}        # Force rollback in production

# Examples
php artisan modular:migrate:rollback Sales --step=2
php artisan modular:migrate:rollback Payment --force
bash
php artisan modular:test {module?}
    {--unit}         # Run only unit tests
    {--feature}      # Run only feature tests
    {--integration}  # Run only integration tests
    {--coverage}     # Generate coverage report
    {--parallel}     # Run tests in parallel

# Examples
php artisan modular:test Sales --coverage
php artisan modular:test Inventory --unit --parallel
php artisan modular:test --feature
bash
php artisan modular:docs {module?}
    {--format=}      # Output format (markdown, html, json)
    {--output=}      # Output directory
    {--api}          # Include API documentation
    {--architecture} # Include architecture diagrams

# Examples
php artisan modular:docs Sales --format=html --api
php artisan modular:docs --architecture --output=docs/
bash
php artisan modular:benchmark
    {--module=}      # Benchmark specific module
    {--iterations=}  # Number of iterations
    {--memory}       # Include memory usage analysis

# Examples
php artisan modular:benchmark --module=Sales --iterations=1000
php artisan modular:benchmark --memory
bash
php artisan modular:stress-test
    {--module=}      # Test specific module
    {--duration=}    # Test duration in seconds
    {--threads=}     # Number of concurrent threads

# Examples
php artisan modular:stress-test --module=Sales --duration=60
php artisan modular:stress-test --threads=10
bash
php artisan modular:optimize:event-store
bash
php artisan modular:health:check
php artisan modular:metrics:show