Modular Monolith in Laravel: Bounded Contexts | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    Modular Monolith in Laravel: Enforcing Bounded Contexts Without a Microservice Tax        On this page       1. [  Why a Modular Monolith? ](#why-a-modular-monolith)
2. [  Directory Structure ](#directory-structure)
3. [  Cross-Boundary Communication via Internal Contracts ](#cross-boundary-communication-via-internal-contracts)
4. [  Enforcing Boundaries with Deptrac ](#enforcing-boundaries-with-deptrac)
5. [  Testing Module Isolation with Pest ](#testing-module-isolation-with-pest)
6. [  Key Takeaways ](#key-takeaways)

  ![Modular Monolith in Laravel: Enforcing Bounded Contexts Without a Microservice Tax](https://cdn.msaied.com/555/c194fc79e9397fef3bcd3a896eb558fd.png)

  #laravel   #architecture   #ddd   #modular-monolith  

 Modular Monolith in Laravel: Enforcing Bounded Contexts Without a Microservice Tax 
====================================================================================

     16 Aug 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said  

       Table of contents

1. [  01   Why a Modular Monolith?  ](#why-a-modular-monolith)
2. [  02   Directory Structure  ](#directory-structure)
3. [  03   Cross-Boundary Communication via Internal Contracts  ](#cross-boundary-communication-via-internal-contracts)
4. [  04   Enforcing Boundaries with Deptrac  ](#enforcing-boundaries-with-deptrac)
5. [  05   Testing Module Isolation with Pest  ](#testing-module-isolation-with-pest)
6. [  06   Key Takeaways  ](#key-takeaways)

 Why a Modular Monolith?
-----------------------

Microservices promise isolation but deliver operational overhead. A well-structured modular monolith gives you the same bounded-context discipline inside a single deployable unit. The key is treating module boundaries as real contracts enforced by tooling, not just folder conventions.

Directory Structure
-------------------

Organise each module under `src/Modules/{Context}/` with a predictable internal layout:

```php
src/
  Modules/
    Billing/
      Actions/
      Data/          # DTOs
      Domain/        # Entities, value objects
      Http/
      Infrastructure/ # Eloquent models, repositories
      Providers/
        BillingServiceProvider.php
      routes.php
    Catalog/
      ...

```

Each module registers itself. `BillingServiceProvider` is the only entry point the framework touches:

```php
// src/Modules/Billing/Providers/BillingServiceProvider.php
namespace App\Modules\Billing\Providers;

use Illuminate\Support\ServiceProvider;

class BillingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(
            \App\Modules\Billing\Domain\Contracts\PaymentGateway::class,
            \App\Modules\Billing\Infrastructure\StripeGateway::class,
        );
    }

    public function boot(): void
    {
        $this->loadRoutesFrom(__DIR__ . '/../routes.php');
        $this->loadMigrationsFrom(__DIR__ . '/../Infrastructure/Migrations');
    }
}

```

Register all module providers in `bootstrap/providers.php` (Laravel 11+) or `config/app.php`.

Cross-Boundary Communication via Internal Contracts
---------------------------------------------------

Modules must never import each other's Eloquent models directly. Define a thin contract in the consuming module:

```php
// src/Modules/Catalog/Domain/Contracts/ProductPricingPort.php
namespace App\Modules\Catalog\Domain\Contracts;

interface ProductPricingPort
{
    public function priceForProduct(string $productId): Money;
}

```

The Billing module provides the adapter:

```php
// src/Modules/Billing/Infrastructure/CatalogPricingAdapter.php
namespace App\Modules\Billing\Infrastructure;

use App\Modules\Catalog\Domain\Contracts\ProductPricingPort;
use App\Modules\Catalog\Domain\ValueObjects\Money;

class CatalogPricingAdapter implements ProductPricingPort
{
    public function priceForProduct(string $productId): Money
    {
        // Billing queries its own read model, not Catalog's Eloquent model
        $row = \DB::table('billing_product_prices')
            ->where('product_id', $productId)
            ->sole();

        return new Money($row->amount_cents, $row->currency);
    }
}

```

Binding lives in `BillingServiceProvider::register()`. Catalog never knows which module satisfies the port.

Enforcing Boundaries with Deptrac
---------------------------------

Folder conventions break under deadline pressure. [Deptrac](https://qossmic.github.io/deptrac/) statically analyses `use` statements and fails CI when a boundary is crossed:

```yaml
# deptrac.yaml
deptrac:
  paths:
    - src/Modules
  layers:
    - name: Billing
      collectors:
        - type: directory
          value: src/Modules/Billing/.*
    - name: Catalog
      collectors:
        - type: directory
          value: src/Modules/Catalog/.*
  ruleset:
    Billing:
      - Catalog   # Billing may depend on Catalog contracts only
    Catalog: ~    # Catalog depends on nothing

```

Run `deptrac analyse` in your GitHub Actions pipeline. Any direct `use App\Modules\Catalog\Infrastructure\` inside Billing fails the build.

Testing Module Isolation with Pest
----------------------------------

Test each module in isolation by binding fakes in the test service provider:

```php
// tests/Modules/Billing/ChargeCustomerActionTest.php
use App\Modules\Billing\Actions\ChargeCustomerAction;
use App\Modules\Billing\Domain\Contracts\PaymentGateway;
use App\Modules\Billing\Tests\Fakes\FakePaymentGateway;

beforeEach(function () {
    $this->fake = new FakePaymentGateway();
    app()->instance(PaymentGateway::class, $this->fake);
});

it('charges the correct amount', function () {
    $action = app(ChargeCustomerAction::class);
    $action->execute(customerId: 'cus_123', amountCents: 4999);

    expect($this->fake->charges())->toHaveCount(1)
        ->and($this->fake->charges()[0]->amountCents)->toBe(4999);
});

```

No database, no HTTP — the module is a self-contained unit.

Key Takeaways
-------------

- **One service provider per module** is the only seam the framework touches.
- **Ports and adapters** prevent Eloquent models from leaking across boundaries.
- **Deptrac in CI** turns architectural rules into failing builds, not suggestions.
- **Pest fakes** let you test domain logic without a running database.
- The modular monolith is a stepping stone: each module can become a microservice later with minimal refactoring because the contracts already exist.

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fmodular-monolith-in-laravel-enforcing-bounded-contexts-without-a-microservice-tax&text=Modular+Monolith+in+Laravel%3A+Enforcing+Bounded+Contexts+Without+a+Microservice+Tax) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fmodular-monolith-in-laravel-enforcing-bounded-contexts-without-a-microservice-tax) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  How is a modular monolith different from just organising code into folders?        Folders are a naming convention. A modular monolith enforces boundaries through service providers as the sole entry point, interface-based cross-module communication, and static analysis tools like Deptrac that fail CI when a boundary is violated. 

      Q02  Can I share Eloquent models between modules?        You should not. Sharing models couples modules at the database schema level. Instead, each module owns its own read models or queries, and exposes data through typed contracts (interfaces returning DTOs or value objects). 

      Q03  Does this approach work with Laravel 11's flat bootstrap structure?        Yes. In Laravel 11 you register module service providers in bootstrap/providers.php. Each module's ServiceProvider handles its own route loading, migration paths, and container bindings independently. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://msaied.com/articles) 

 [ ![Octane Worker Lifecycle, State Leakage, and Memory Management in Production](https://cdn.msaied.com/554/8cc265358b47e59601a66d1e247eba9a.png) laravel octane performance 

### Octane Worker Lifecycle, State Leakage, and Memory Management in Production

Laravel Octane keeps workers alive across requests, which means static state, resolved singletons, and stale d...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 16 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/octane-worker-lifecycle-state-leakage-and-memory-management-in-production-2) [ ![Job Batching with Laravel Horizon: Reliable Async Workflows at Scale](https://cdn.msaied.com/553/b794b736bfd84f3cbcc6218319916544.png) laravel queues horizon 

### Job Batching with Laravel Horizon: Reliable Async Workflows at Scale

Learn how to combine Laravel's job batching API with Horizon's queue supervision to build fault-tolerant async...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 15 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/job-batching-with-laravel-horizon-reliable-async-workflows-at-scale) [ ![Contextual Eloquent Casts: Custom Cast Classes, Value Objects, and Inbound-Only Transforms](https://cdn.msaied.com/552/a7825c0c6f53d934f84fce522573eafb.png) laravel eloquent value-objects 

### Contextual Eloquent Casts: Custom Cast Classes, Value Objects, and Inbound-Only Transforms

Go beyond primitive casts. Learn how to build custom Eloquent cast classes that hydrate value objects, handle...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 15 Aug 2026     1 min read  

  Read    

 ](https://msaied.com/articles/contextual-eloquent-casts-custom-cast-classes-value-objects-and-inbound-only-transforms) 

   [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

Explore

- [Home](https://msaied.com)
- [Projects](https://msaied.com/projects)
- [Articles](https://msaied.com/articles)
- [Certificates](https://msaied.com/certificates)
- [Contact](https://msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
