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
}
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();