DEV Community

Cover image for Untangling Dependency Cycles in a Modular Laravel Monolith
Muhammad Ali Mughal
Muhammad Ali Mughal

Posted on

Untangling Dependency Cycles in a Modular Laravel Monolith

Once the strangler fig from Part 1 is working, the new Laravel app grows fast. Each migrated route brings a feature with it: dealers, orders, invoices, stock. Teams usually organise that into modules, something like app/Modules/Orders, app/Modules/Billing, app/Modules/Inventory. For a few months it feels clean. Then someone adds a call from Billing into Orders to check a status, someone else adds a call from Orders into Billing to fetch a price, and a year later every module imports every other one. You have rebuilt the legacy ball of mud, only with nicer folders.

I see this pattern often enough that I now add a dependency check before the second module exists. This post shows how to find cycles in an existing modular Laravel app, how to break them without a rewrite, and how to stop them from coming back.

I wrote this with help from AI tools and checked the commands against the deptrac and Laravel documentation. I am a Principal Software Engineer in Karachi with 9+ years across PHP/Laravel, Vue, Node and .NET microservices, and this is how we structure modernization projects at Loop Origin.

๐Ÿ“š Series Navigation โ€” Modernizing Legacy PHP Without a Rewrite

  • Part 1: Strangler Fig for Legacy PHP: Run Old and New Side by Side
  • Part 2 (This Post): Untangling Dependency Cycles in a Modular Laravel Monolith
  • Part 3: Upgrading Old PHP Versions Safely With Rector and CI
  • Part 4: Replacing Legacy Auth & Sessions Without Logging Everyone Out
  • Part 5: From FTP Deploys and Cron Scripts to a Real Pipeline
  • Part 6: Decommissioning the Old App: Shadow Traffic, Flags & Final Cutover

Related earlier posts: Characterization Tests Before You Refactor AI-Written Code ยท Zero-Downtime Database Migrations in Laravel & Node.js SaaS

How do you fix dependency cycles in a modular Laravel app?

Direct answer: Map which modules import which with a tool like deptrac, pick a direction for each relationship, and break every reverse edge. Use a published interface (contract) for synchronous reads, domain events for reactions, and an anti-corruption layer for legacy data. Then fail CI on any new violation.

Organized workshop shelves and tools, AI-generated

Why cycles hurt

A cycle between two modules means neither can change, be tested or be extracted alone. In practice it shows up as:

  • Tests that boot half the app. A unit test for Billing needs Orders factories, which need Inventory seeders.
  • Changes that ripple. Renaming a column in Orders breaks a query in Billing that nobody knew about.
  • Impossible extraction. If you ever want to move Billing into its own service, you cannot, because it is woven into everything.

The goal is not zero dependencies. It is a dependency graph that points in one direction, so lower modules never know about higher ones.

Step 1: see the graph

Start by measuring. deptrac lets you declare layers (here, modules) and reports every class-level dependency between them. A minimal config for a modular Laravel app:

# deptrac.yaml
deptrac:
  paths: ["./app/Modules"]
  layers:
    - { name: Orders,    collectors: [{ type: directory, value: app/Modules/Orders/.* }] }
    - { name: Billing,   collectors: [{ type: directory, value: app/Modules/Billing/.* }] }
    - { name: Inventory, collectors: [{ type: directory, value: app/Modules/Inventory/.* }] }
    - { name: Shared,    collectors: [{ type: directory, value: app/Modules/Shared/.* }] }
  ruleset:
    Orders:    [Inventory, Shared, Billing]
    Billing:   [Shared]
    Inventory: [Shared]
    Shared:    []
Enter fullscreen mode Exit fullscreen mode

Run vendor/bin/deptrac analyse and it lists every violation with file and line. On the first run in an older codebase, expect dozens. Do not try to fix them all at once. Record the current state as a baseline (deptrac analyse --formatter=baseline), so CI only fails on new violations while you work through the old ones.

If you just want a quick picture before installing anything, a crude import count already tells you where the knots are:

for m in Orders Billing Inventory; do
  echo "== $m imports:"
  grep -rhoE "use App\\\\Modules\\\\[A-Za-z]+" app/Modules/$m \
    | sed 's/.*Modules\\//' | sort | uniq -c | grep -v " $m$"
done
Enter fullscreen mode Exit fullscreen mode

Step 2: decide the direction

For each pair of modules that depend on each other, decide which one is "lower". My rule of thumb: the module that would still make sense if the other disappeared is lower. Billing can exist without knowing about order screens; Orders cannot place an order without a price. So Orders may depend on Billing, and Billing must not depend on Orders.

Step 3: break each reverse edge

There are three tools, and choosing the right one for each edge matters:

Technique Use when Example Trade-off
Contract (interface) The lower module needs to call the higher one synchronously for data Billing needs order totals: define OrderTotals in Billing, implement it in Orders Still a runtime link, but the direction is inverted
Domain event The lower module only needs to react after something happens Billing listens to OrderPlaced to create an invoice Eventual consistency, needs idempotent listeners
Anti-corruption layer A module keeps reaching into legacy tables or another module's models Inventory reads old tbl_stock through a LegacyStockReader Extra mapping code, but isolates the mess

Contract: invert the dependency

The lower module owns the interface; the higher module implements it and binds it in its service provider.

// app/Modules/Billing/Contracts/OrderTotals.php
namespace App\Modules\Billing\Contracts;

interface OrderTotals
{
    public function forOrder(int $orderId): Money;
}

// app/Modules/Orders/Billing/EloquentOrderTotals.php
final class EloquentOrderTotals implements \App\Modules\Billing\Contracts\OrderTotals
{
    public function forOrder(int $orderId): Money
    {
        return Money::ofMinor(Order::findOrFail($orderId)->lines()->sum('total_minor'), 'USD');
    }
}

// app/Modules/Orders/OrdersServiceProvider.php
$this->app->bind(OrderTotals::class, EloquentOrderTotals::class);
Enter fullscreen mode Exit fullscreen mode

Billing now depends only on its own interface. deptrac sees Orders โ†’ Billing, which is the allowed direction.

Event: react without importing

// Orders dispatches, knowing nothing about who listens
OrderPlaced::dispatch($order->id, $order->tenant_id);

// Billing listens, idempotently
final class CreateInvoiceForOrder implements ShouldQueue
{
    public function handle(OrderPlaced $e): void
    {
        Invoice::firstOrCreate(['order_id' => $e->orderId], [...]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Keep event classes in a small shared module, or in the producing module with plain scalar payloads, so listeners never need the producer's Eloquent models.

Step 4: stop passing models across modules

The most common source of new cycles is an Eloquent model from one module showing up in another module's method signatures. Once Billing accepts an Orders\Models\Order, it can lazy-load anything. Pass ids or small read-only DTOs across module boundaries instead. It feels like extra typing for a week and saves months later.

Step 5: guard it in CI

# .github/workflows/ci.yml (excerpt)
- name: Module boundaries
  run: vendor/bin/deptrac analyse --fail-on-uncovered --report-uncovered --no-progress
Enter fullscreen mode Exit fullscreen mode

With the baseline in place, this blocks any pull request that adds a new reverse dependency, while the team burns down the old ones a few per sprint. On our projects, we treat the baseline count as a number on the migration ledger from Part 1: it should only go down.

If your modular monolith has already tangled and you want a second pair of eyes, our Laravel development page explains how we approach these refactors, and you can contact us with a short description of the modules involved.

Diagnostic checklist

  • [ ] Every module has a declared layer in deptrac (or a similar tool)
  • [ ] The allowed dependency direction is written down for each module pair
  • [ ] A baseline captures existing violations so CI only blocks new ones
  • [ ] Reverse synchronous calls go through interfaces owned by the lower module
  • [ ] Reactions use domain events with scalar payloads and idempotent listeners
  • [ ] Legacy table access sits behind an anti-corruption layer
  • [ ] No Eloquent model crosses a module boundary in a method signature
  • [ ] The baseline violation count goes down every sprint

FAQ

Do I need a package like nWidart/laravel-modules for this?

No. Plain folders under app/Modules with their own service providers are enough. A package can help with scaffolding, but boundaries come from rules and CI, not from the folder tool.

Is deptrac the only option?

No. PHPArch and PHPat can express similar rules as tests, and some teams write a small custom PHPStan rule. Pick one and run it in CI; the tool matters less than enforcing it.

Will events make the app harder to debug?

A little. Log the event name and correlation id when it is dispatched and handled, so you can follow a request across modules in your logs.

What goes in the Shared module?

As little as possible: value objects like Money, base exceptions and event classes. If Shared starts holding business logic, it becomes the new tangle.

Should modules have separate databases?

Not at this stage. Separate table ownership, enforced in code, is enough. Splitting databases only makes sense if you later extract a module into its own service.

How long does untangling take?

On a mid-sized app, the first baseline and CI rule take a day. Burning down the old violations is ongoing work, usually spread across a few months alongside features.

Next in this series, Part 3 covers upgrading old PHP versions safely with Rector and CI.


Follow & Connect

Top comments (0)