PHP code example of mghrby / laravel-modular-ddd

1. Go to this page and download the library: Download mghrby/laravel-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 / laravel-modular-ddd example snippets


/**
 * @OA\Get(
 *     path="/api/v1/posts",
 *     operationId="listPostsv1",
 *     tags={"Post"},
 *     summary="Get paginated list of Posts",
 *     description="Retrieve a paginated list of Posts with optional filtering, sorting, and pagination parameters.",
 *     security={{"bearerAuth": {}}, {"oauth2": {}}},
 *     @OA\Parameter(name="page", in="query", description="Page number for pagination", /Post")),
 *             @OA\Property(property="links", type="object", example={"first": "http://localhost/api/v1/posts?page=1", "last": "http://localhost/api/v1/posts?page=5", "prev": null, "next": "http://localhost/api/v1/posts?page=2"}),
 *             @OA\Property(property="meta", type="object", example={"current_page": 1, "from": 1, "last_page": 5, "per_page": 15, "to": 15, "total": 67})
 *         )
 *     ),
 *     @OA\Response(response=401, description="Unauthenticated", @OA\JsonContent(@OA\Property(property="message", type="string", example="Unauthenticated."))),
 *     @OA\Response(response=403, description="Forbidden", @OA\JsonContent(@OA\Property(property="message", type="string", example="This action is unauthorized."))),
 *     @OA\Response(response=500, description="Internal Server Error", @OA\JsonContent(@OA\Property(property="message", type="string", example="Internal server error occurred")))
 * )
 */
public function index(): JsonResponse
{
    // Controller implementation
}

'api' => [
    'documentation' => [
        'swagger' => [
            // Enable comprehensive documentation by default
            'enabled' => env('MODULAR_DDD_SWAGGER_ENABLED', true),

            // Documentation metadata
            'title' => env('MODULAR_DDD_SWAGGER_TITLE', 'Laravel Modular DDD API'),
            'description' => env('MODULAR_DDD_SWAGGER_DESCRIPTION', 'Comprehensive API documentation for modular application'),
            'version' => env('MODULAR_DDD_SWAGGER_VERSION', '1.0.0'),

            // Contact information
            'contact' => [
                'name' => env('MODULAR_DDD_SWAGGER_CONTACT_NAME', 'API Support'),
                'url' => env('MODULAR_DDD_SWAGGER_CONTACT_URL', ''),
                'email' => env('MODULAR_DDD_SWAGGER_CONTACT_EMAIL', ''),
            ],

            // Security schemes
            'security' => [
                'bearer_auth' => env('MODULAR_DDD_SWAGGER_BEARER_AUTH', true),
                'oauth2' => env('MODULAR_DDD_SWAGGER_OAUTH2_AUTH', true),
                'api_key' => env('MODULAR_DDD_SWAGGER_API_KEY_AUTH', false),
            ],

            // Generation settings
            'generation' => [
                'comprehensive_by_default' => env('MODULAR_DDD_SWAGGER_COMPREHENSIVE_DEFAULT', true),
                'auto_examples' => env('MODULAR_DDD_SWAGGER_AUTO_EXAMPLES', true),
                '

// Automatically detected when Laravel Passport is installed
'oauth2_flows' => [
    'authorizationCode' => [
        'authorizationUrl' => config('app.url') . '/oauth/authorize',
        'tokenUrl' => config('app.url') . '/oauth/token',
        'scopes' => [
            '*' => 'Full access to API',
            'read' => 'Read access to resources',
            'write' => 'Write access to resources',
        ],
    ],
    'clientCredentials' => [
        'tokenUrl' => config('app.url') . '/oauth/token',
        'scopes' => [
            '*' => 'Full access to API',
        ],
    ],
],

Schema::create('orders', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('name');
    $table->text('description')->nullable();
    $table->timestamps();

    // Smart indexes for performance
    $table->index(['created_at']);
    $table->index(['name']);
});

// Using helper functions
$command = new CreateProductCommand('iPhone 15', 999.99, 'Electronics');
$product = dispatch_command($command);

$query = new GetProductQuery($productId);
$productData = ask_query($query);

// Using facades
use TaiCrm\LaravelModularDdd\Foundation\Facades\CommandBus;
use TaiCrm\LaravelModularDdd\Foundation\Facades\QueryBus;

$product = CommandBus::dispatch(new CreateProductCommand($name, $price, $category));
$productData = QueryBus::ask(new GetProductQuery($productId));

// Using dependency injection
class ProductController extends Controller
{
    public function __construct(
        private CommandBus $commandBus,
        private QueryBus $queryBus
    ) {}

    public function store(CreateProductRequest $request)
    {
        $command = new CreateProductCommand(...$request->validated());
        $product = $this->commandBus->dispatch($command);

        return new ProductResource($product);
    }
}

// Using version-aware routes in modules/YourModule/Routes/api.php
Route::prefix('api/{version}')
    ->middleware(['api', 'api.version'])
    ->where('version', 'v[1-2]')
    ->group(function () {
        Route::apiResource('users', UserController::class);
    });

// Version-specific controllers
// modules/UserModule/Http/Controllers/Api/V1/UserController.php
class UserController extends Controller
{
    public function index()
    {
        // v1 implementation
        return UserResource::collection(User::all());
    }
}

// modules/UserModule/Http/Controllers/Api/V2/UserController.php
class UserController extends Controller
{
    public function index()
    {
        // v2 implementation with enhanced features
        return UserResource::collection(
            User::with('profile', 'preferences')->get()
        );
    }
}

// Custom version transformations
use TaiCrm\LaravelModularDdd\Http\Compatibility\BaseRequestTransformer;

class UserV1ToV2RequestTransformer extends BaseRequestTransformer
{
    protected function getDescription(): string
    {
        return 'Transform user requests from v1 to v2';
    }

    public function transform(Request $request, string $fromVersion, string $toVersion): Request
    {
        $data = $request->all();

        // Transform old 'full_name' field to 'first_name' and 'last_name'
        if (isset($data['full_name'])) {
            $names = explode(' ', $data['full_name'], 2);
            $data['first_name'] = $names[0];
            $data['last_name'] = $names[1] ?? '';
            unset($data['full_name']);
        }

        return $this->cloneRequest($request)->replace($data);
    }
}

// Register transformers in a service provider
$registry = app(TransformationRegistry::class);
$registry->registerRequestTransformer('v1', 'v2', new UserV1ToV2RequestTransformer('v1', 'v2'));

// In your User model
use TaiCrm\LaravelModularDdd\Authorization\Traits\HasModulePermissions;

class User extends Authenticatable
{
    use HasModulePermissions;

    // ... your existing code
}

// Grant permissions programmatically
$user = User::find(1);
$user->grantModulePermission('ProductModule', 'view-products');
$user->grantModulePermissions('ProductModule', ['create-products', 'update-products']);

// Check permissions
if ($user->hasModulePermission('ProductModule', 'view-products')) {
    // User can view products
}

// In routes/web.php or routes/api.php
Route::middleware(['auth', 'module.permission:product-module.view-products'])
    ->get('/products', [ProductController::class, 'index']);

Route::middleware(['auth', 'module.role:product-module.admin'])
    ->delete('/products/{product}', [ProductController::class, 'destroy']);

// Automatic monitoring with middleware
use TaiCrm\LaravelModularDdd\Monitoring\EnhancedPerformanceMiddleware;

// Global middleware in app/Http/Kernel.php
protected $middleware = [
    EnhancedPerformanceMiddleware::class,
];

// Manual performance monitoring
use TaiCrm\LaravelModularDdd\Monitoring\QueryPerformanceAnalyzer;

$analyzer = app(QueryPerformanceAnalyzer::class);
$analyzer->startMonitoring();

// Your database operations
User::with('products')->get();

$report = $analyzer->stopMonitoring();
// Check for slow queries and N+1 issues
$slowQueries = $analyzer->getSlowQueries();
$nPlusOneQueries = $analyzer->detectNPlusOneQueries();



return [
    /*
    |--------------------------------------------------------------------------
    | Modules Path
    |--------------------------------------------------------------------------
    */
    'modules_path' => base_path('modules'),

    /*
    |--------------------------------------------------------------------------
    | Auto Discovery
    |--------------------------------------------------------------------------
    */
    'auto_discovery' => true,

    /*
    |--------------------------------------------------------------------------
    | Monitoring Configuration
    |--------------------------------------------------------------------------
    */
    'monitoring' => [
        'enabled' => true,
        'query_threshold' => 1000, // milliseconds
        'memory_threshold' => 128 * 1024 * 1024, // 128MB
        'cache_enabled' => true,
    ],

    /*
    |--------------------------------------------------------------------------
    | Authorization Models
    |--------------------------------------------------------------------------
    */
    'models' => [
        'user_module_permission' => 'App\Models\UserModulePermission',
        'user_module_role' => 'App\Models\UserModuleRole',
    ],

    /*
    |--------------------------------------------------------------------------
    | Security Configuration
    |--------------------------------------------------------------------------
    */
    'security' => [
        'scan_enabled' => true,
        'vulnerability_check' => true,
        'dependency_check' => true,
    ],

    /*
    |--------------------------------------------------------------------------
    | Performance Configuration
    |--------------------------------------------------------------------------
    */
    'performance' => [
        'query_logging' => true,
        'cache_monitoring' => true,
        'resource_tracking' => true,
        'alerts_enabled' => true,
    ],

    /*
    |--------------------------------------------------------------------------
    | API Versioning Configuration
    |--------------------------------------------------------------------------
    */
    'api' => [
        'prefix' => 'api',
        'middleware' => ['api'],

        // Multi-version support configuration
        'versions' => [
            'supported' => ['v1', 'v2'],
            'default' => 'v2',
            'latest' => 'v2',
            'deprecated' => ['v1'],
            'sunset_dates' => [
                'v1' => '2025-12-31',
            ],
        ],

        // Version negotiation configuration
        'negotiation' => [
            'strategy' => 'url,header,query,default',
            'headers' => ['Accept-Version', 'X-API-Version'],
        ],

        // Backward compatibility settings
        'compatibility' => [
            'auto_transform' => true,
            'request_transformation' => true,
            'response_transformation' => true,
        ],

        // Documentation and discovery
        'documentation' => [
            'discovery_endpoint' => '/api/versions',
            '



return [
    // Basic CRUD permissions
    'view-products' => [
        'description' => 'View products list and details',
        'group' => 'products',
    ],
    'create-products' => [
        'description' => 'Create new products',
        'group' => 'products',
        'dependencies' => ['view-products'],
    ],
    'update-products' => [
        'description' => 'Update existing products',
        'group' => 'products',
        'dependencies' => ['view-products'],
    ],
    'delete-products' => [
        'description' => 'Delete products',
        'group' => 'products',
        'dependencies' => ['view-products'],
    ],

    // Advanced permissions
    'manage-inventory' => [
        'description' => 'Manage product inventory levels',
        'group' => 'inventory',
        'dependencies' => ['view-products'],
    ],
    'export-products' => [
        'description' => 'Export product data',
        'group' => 'data',
        'dependencies' => ['view-products'],
    ],
    'manage-categories' => [
        'description' => 'Manage product categories',
        'group' => 'administration',
    ],
];

// Create migration: create_user_module_permissions_table
Schema::create('user_module_permissions', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->string('module_id');
    $table->string('permission');
    $table->timestamp('granted_at');
    $table->timestamps();

    $table->unique(['user_id', 'module_id', 'permission']);
    $table->index(['module_id', 'permission']);
});

// Create migration: create_user_module_roles_table
Schema::create('user_module_roles', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->string('module_id');
    $table->string('role');
    $table->timestamp('granted_at');
    $table->timestamps();

    $table->unique(['user_id', 'module_id', 'role']);
    $table->index(['module_id', 'role']);
});
bash
# Publish configuration files
php artisan vendor:publish --provider="TaiCrm\LaravelModularDdd\ModularDddServiceProvider" --tag="config"

# Publish stub templates (optional)
php artisan vendor:publish --provider="TaiCrm\LaravelModularDdd\ModularDddServiceProvider" --tag="stubs"
bash
# Create domain events and listeners
php artisan module:make-event {Module} {EventName} [--aggregate={Name}]
php artisan module:make-listener {Module} {ListenerName} [--event={EventName}]

# Examples:
php artisan module:make-event UserModule UserRegistered --aggregate=User
php artisan module:make-listener UserModule SendWelcomeEmail --event=UserRegistered
bash
# Generate intelligent tests
php artisan module:make-test {Module} {TestName} [--type={unit|feature|integration}]
php artisan module:make-factory {Module} {ModelName}

# Examples:
php artisan module:make-test UserModule UserServiceTest --type=unit
php artisan module:make-test UserModule UserApiTest --type=feature
php artisan module:make-factory UserModule User
bash
# Create authorization policies
php artisan module:make-policy {Module} {PolicyName} [--model={Name}] [--resource] [--api]

# Examples:
php artisan module:make-policy UserModule UserPolicy --model=User --resource
php artisan module:make-policy UserModule UserApiPolicy --model=User --resource --api
bash
# Create custom validation rules
php artisan module:make-rule {Module} {RuleName}

# Examples:
php artisan module:make-rule UserModule Uppercase
php artisan module:make-rule UserModule ValidEmail
php artisan module:make-rule UserModule StrongPassword
bash
# Verify Passport installation
php artisan passport:client --personal

# Check OAuth2 configuration
php artisan route:list | grep oauth

# Validate security schemes
php artisan module:swagger:validate --strict
bash
# Creates module + migration automatically
php artisan module:make OrderModule --aggregate=Order
# ✅ Creates: modules/OrderModule/Database/Migrations/xxxx_create_orders_table.php
bash
# Run module migrations
php artisan module:migrate {ModuleName}
php artisan module:migrate --all

# Run module seeders
php artisan module:seed {ModuleName}
php artisan module:seed --all

# Rollback module migrations
php artisan module:migrate:rollback {ModuleName}
bash
# Comprehensive health check
php artisan module:health {ModuleName}
php artisan module:health --all

# Check specific health aspects
php artisan module:health {ModuleName} --dependencies
php artisan module:health {ModuleName} --performance
bash
# Security vulnerability scan
php artisan module:security {ModuleName}
php artisan module:security --all

# Export security report
php artisan module:security {ModuleName} --export=security-report.json
bash
# Watch modules for file changes
php artisan module:dev watch

# Generate dependency visualization
php artisan module:visualization

# Show module metrics
php artisan module:metrics {ModuleName}

# Generate DDD components
php artisan module:stub {ComponentType} {Name} {ModuleName}
bash
# Check module status
php artisan module:status ModuleName

# Verify dependencies
php artisan module:health ModuleName --dependencies

# Clear and rebuild cache
php artisan module:cache clear
php artisan module:cache rebuild
bash
# Sync permissions
php artisan module:permission sync

# Check user permissions
php artisan module:permission matrix [email protected]

# Verify permission configuration
php artisan module:permission list --module=ModuleName