Laravel Modular Monolith: Bounded Contexts Guide | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Modular Monolith in Laravel: Enforcing Bounded Contexts Without a Microservices Tax

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

 Learn how to carve a Laravel application into cohesive bounded contexts using modules, internal contracts, and Pest architecture tests — without splitting into microservices.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 21 Jul 2026 · Updated 21 Jul 2026 · 3 min read

ShareCopy linkCopied

 ![Modular Monolith in Laravel: Enforcing Bounded Contexts Without a Microservices Tax](https://cdn.msaied.com/451/014ea4597c12e3ba1ce7a4f4a33d299e.png) 

  On this page +1. [Why a Modular Monolith?](#why-a-modular-monolith)
2. [Directory Layout](#directory-layout)
3. [Registering Modules Automatically](#registering-modules-automatically)
4. [Defining a Public Contract](#defining-a-public-contract)
5. [Preventing Accidental Coupling with Pest Architecture Tests](#preventing-accidental-coupling-with-pest-architecture-tests)
6. [Cross-Module Communication via Events](#cross-module-communication-via-events)
7. [Database Boundaries](#database-boundaries)
8. [Takeaways](#takeaways)

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

Microservices solve distribution problems you probably don't have yet. A modular monolith gives you the domain isolation of microservices while keeping a single deployment unit, a shared database transaction, and zero network overhead between modules. The trick is enforcing the boundaries so the monolith never becomes a big ball of mud.

Directory Layout
----------------

Organise by bounded context, not by technical layer:

```php
app/
  Modules/
    Billing/
      Actions/
      Data/          # DTOs, value objects
      Events/
      Http/
      Models/
      Providers/
      Contracts/     # public interface for other modules
    Inventory/
      ...
    Shared/
      ...

```

Each module owns its own `ServiceProvider`. The `Shared` module holds cross-cutting concerns (money value objects, pagination DTOs, etc.) that every module may import. Nothing outside `Contracts/` is a stable API.

Registering Modules Automatically
---------------------------------

Add a `ModuleServiceProvider` that discovers and boots every module:

```php
// app/Providers/ModuleServiceProvider.php
class ModuleServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        foreach (glob(app_path('Modules/*/Providers/*ServiceProvider.php')) as $file) {
            $class = $this->classFromPath($file);
            $this->app->register($class);
        }
    }

    private function classFromPath(string $path): string
    {
        return str_replace(
            [app_path() . '/', '/', '.php'],
            ['App/', '\\', ''],
            $path
        );
    }
}

```

Register `ModuleServiceProvider` in `bootstrap/providers.php` (Laravel 11+) and every new module is picked up without touching any central file.

Defining a Public Contract
--------------------------

A module exposes only what other modules need:

```php
// app/Modules/Billing/Contracts/BillingService.php
interface BillingService
{
    public function charge(CustomerId $customer, Money $amount): Receipt;
    public function currentPlan(CustomerId $customer): Plan;
}

```

The concrete implementation lives inside `Billing` and is bound in `BillingServiceProvider`:

```php
$this->app->bind(BillingService::class, StripeBillingService::class);

```

The `Inventory` module injects `BillingService`, never `StripeBillingService`. This is the boundary.

Preventing Accidental Coupling with Pest Architecture Tests
-----------------------------------------------------------

Pest's `arch()` helper lets you codify boundaries as executable tests:

```php
// tests/Architecture/ModuleBoundariesTest.php
arch('Inventory does not reach into Billing internals')
    ->expect('App\Modules\Inventory')
    ->not->toUse('App\Modules\Billing\Actions')
    ->not->toUse('App\Modules\Billing\Models');

arch('Billing only exposes its Contracts namespace')
    ->expect('App\Modules\Billing\Actions')
    ->not->toBeUsedIn('App\Modules\Inventory');

arch('Shared module has no module-specific imports')
    ->expect('App\Modules\Shared')
    ->not->toUse('App\Modules\Billing')
    ->not->toUse('App\Modules\Inventory');

```

These tests run in milliseconds and fail the CI pipeline the moment a developer reaches across a boundary.

Cross-Module Communication via Events
-------------------------------------

When `Billing` needs to tell `Inventory` that a subscription was cancelled, it dispatches a domain event rather than calling an `Inventory` class directly:

```php
// Billing dispatches:
event(new SubscriptionCancelled($customerId, $plan, now()));

// Inventory listens:
class FreezeInventoryAllotment
{
    public function handle(SubscriptionCancelled $event): void
    {
        // Inventory-specific logic only
    }
}

```

The event lives in `Billing\Events` (the source of truth). `Inventory` depends on the event class — that's acceptable because events are part of the public contract surface.

Database Boundaries
-------------------

You share one database, but each module should prefix its tables (`billing_invoices`, `inventory_products`). Avoid cross-module Eloquent relationships; use IDs and re-query inside the target module. This keeps migrations independent and makes a future extraction to a separate service mechanical rather than surgical.

Takeaways
---------

- Organise by bounded context; let each module own its `ServiceProvider`.
- Expose only `Contracts/` interfaces — never concrete classes or internal models.
- Use Pest `arch()` tests to make boundary violations a CI failure, not a code-review debate.
- Communicate across modules with domain events, not direct method calls.
- Prefix tables per module so schema ownership is unambiguous.
- A modular monolith is the right default; extract to microservices only when you have a proven scaling or team-autonomy reason.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [architecture](https://www.msaied.com/public/articles?search=architecture)
- [ddd](https://www.msaied.com/public/articles?search=ddd)
- [modular-monolith](https://www.msaied.com/public/articles?search=modular-monolith)

 Frequently asked questions 
---------------------------

  Can modules share an Eloquent model, for example a shared User?Avoid it. Instead, each module that needs user data should define a thin read model or query its own projection. If a shared User is unavoidable, place it in the Shared module and treat it as a stable, rarely-changing contract.

   How do Pest architecture tests differ from PHPStan for enforcing boundaries?PHPStan catches type errors and undefined references. Pest arch() tests express intentional architectural rules — 'this namespace must not use that namespace' — which PHPStan has no concept of. Both tools are complementary; use PHPStan for type safety and Pest arch() for boundary enforcement.

   When should I actually split a module into a separate service?When a module has a genuinely different scaling profile, needs independent deployment cadence, or a separate team owns it end-to-end. Organisational and operational reasons justify the distribution tax; technical complexity alone rarely does.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

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

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleDDD Value Objects and DTOs in Laravel Without the Bloat](https://www.msaied.com/public/articles/ddd-value-objects-and-dtos-in-laravel-without-the-bloat) [Next articleRouteKey Model Attribute and More: What's New in Laravel 13.21](https://www.msaied.com/public/articles/routekey-model-attribute-and-more-whats-new-in-laravel-1321)  

   On this page
-------------

1. [Why a Modular Monolith?](#why-a-modular-monolith)
2. [Directory Layout](#directory-layout)
3. [Registering Modules Automatically](#registering-modules-automatically)
4. [Defining a Public Contract](#defining-a-public-contract)
5. [Preventing Accidental Coupling with Pest Architecture Tests](#preventing-accidental-coupling-with-pest-architecture-tests)
6. [Cross-Module Communication via Events](#cross-module-communication-via-events)
7. [Database Boundaries](#database-boundaries)
8. [Takeaways](#takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
