Language:

Search

How to Structure Laravel App for Domain Driven Design

  • Share this:
How to Structure Laravel App for Domain Driven Design

In Domain-Driven Design (DDD), the focus is on organising the code around the business domain. In Laravel, you can structure your files using the DDD approach by creating a folder for each domain or bounded context. This will make your code more modular, maintainable, and scalable. Here's an example of a DDD structure in a Laravel project:

app/
|-- Console/
|-- Exceptions/
|-- Http/
|-- Providers/
|-- Domain/ (or src/)
    |-- Product/
        |-- Models/
            |-- Product.php
        |-- Repositories/
            |-- EloquentProductRepository.php
            |-- ProductRepositoryInterface.php
        |-- Services/
            |-- ProductService.php
        |-- Events/
            |-- ProductCreated.php
        |-- Policies/
            |-- ProductPolicy.php
        |-- Requests/
            |-- CreateProductRequest.php
            |-- UpdateProductRequest.php
        |-- Resources/
            |-- ProductResource.php
        |-- Controllers/
            |-- ProductController.php
    |-- User/
        |-- Models/
            |-- User.php
        |-- Repositories/
            |-- EloquentUserRepository.php
            |-- UserRepositoryInterface.php
        |-- Services/
            |-- UserService.php
        |-- Events/
            |-- UserRegistered.php
        |-- Policies/
            |-- UserPolicy.php
        |-- Requests/
            |-- CreateUserRequest.php
            |-- UpdateUserRequest.php
        |-- Resources/
            |-- UserResource.php
        |-- Controllers/
            |-- UserController.php
config/
database/
public/
resources/
routes/
storage/
tests/
vendor/

In this example, the project has two domains: Product and User. Each domain folder contains relevant Models, Repositories, Services, Events, Policies, Requests, Resources, and Controllers. This approach allows for better separation of concerns, keeping the codebase clean and organised.

Also Read: Laravel Livewire Commenting System

Remember to update the namespaces in each file to match the new folder structure. Also, don't forget to update the PSR-4 autoloading configuration in the composer.json file:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "App\\Domain\\": "app/Domain/"
    }
},

After modifying the composer.json file, run composer dump-autoload to regenerate the autoloading files.

Related: 
 

Handle routes in Laravel for DDD 

Subdomain routes in Laravel for DDD 

TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques