{"slug": "untangling-dependency-cycles-in-a-modular-laravel-monolith", "title": "Untangling Dependency Cycles in a Modular Laravel Monolith", "summary": "A principal software engineer at Loop Origin published a guide on detecting and breaking dependency cycles in modular Laravel monoliths, using the deptrac static analysis tool to map class-level imports between modules such as Orders, Billing and Inventory. The approach records existing violations as a baseline so CI fails only on new cycles, then breaks reverse edges with published interfaces for synchronous reads, domain events for reactions, and an anti-corruption layer for legacy data.", "body_md": "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.\n\nI 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.\n\nI 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](https://looporigin.com/?utm_source=devto&utm_medium=series&utm_campaign=dependency-cycles-modular-laravel).\n\n**📚 Series Navigation — Modernizing Legacy PHP Without a Rewrite**\n\n**Part 1:** [Strangler Fig for Legacy PHP: Run Old and New Side by Side](https://dev.to/muhammadalimughal/strangler-fig-for-legacy-php-run-old-and-new-side-by-side-56mm)\n**Part 2 (This Post):** Untangling Dependency Cycles in a Modular Laravel Monolith\n**Part 3:** Upgrading Old PHP Versions Safely With Rector and CI\n**Part 4:** Replacing Legacy Auth & Sessions Without Logging Everyone Out\n**Part 5:** From FTP Deploys and Cron Scripts to a Real Pipeline\n**Part 6:** Decommissioning the Old App: Shadow Traffic, Flags & Final Cutover\n*Related earlier posts:* [Characterization Tests Before You Refactor AI-Written Code](https://dev.to/muhammadalimughal/characterization-tests-before-you-refactor-ai-written-code-26l7) · [Zero-Downtime Database Migrations in Laravel & Node.js SaaS](https://dev.to/muhammadalimughal/zero-downtime-database-migrations-in-laravel-nodejs-saas-expand-contract-lock-timeouts-6lp)\n\n**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.\n\nA cycle between two modules means neither can change, be tested or be extracted alone. In practice it shows up as:\n\nThe goal is not zero dependencies. It is a dependency graph that points in one direction, so lower modules never know about higher ones.\n\nStart by measuring. [deptrac](https://github.com/deptrac/deptrac) lets you declare layers (here, modules) and reports every class-level dependency between them. A minimal config for a modular Laravel app:\n\n```\n# deptrac.yaml\ndeptrac:\n  paths: [\"./app/Modules\"]\n  layers:\n    - { name: Orders,    collectors: [{ type: directory, value: app/Modules/Orders/.* }] }\n    - { name: Billing,   collectors: [{ type: directory, value: app/Modules/Billing/.* }] }\n    - { name: Inventory, collectors: [{ type: directory, value: app/Modules/Inventory/.* }] }\n    - { name: Shared,    collectors: [{ type: directory, value: app/Modules/Shared/.* }] }\n  ruleset:\n    Orders:    [Inventory, Shared, Billing]\n    Billing:   [Shared]\n    Inventory: [Shared]\n    Shared:    []\n```\n\nRun `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.\n\nIf you just want a quick picture before installing anything, a crude import count already tells you where the knots are:\n\n```\nfor m in Orders Billing Inventory; do\n  echo \"== $m imports:\"\n  grep -rhoE \"use App\\\\\\\\Modules\\\\\\\\[A-Za-z]+\" app/Modules/$m \\\n    | sed 's/.*Modules\\\\//' | sort | uniq -c | grep -v \" $m$\"\ndone\n```\n\nFor 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.\n\nThere are three tools, and choosing the right one for each edge matters:\n\n| Technique | Use when | Example | Trade-off | \n|---|---|---|---|\n| 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 | \n| 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 | \n| 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 | \n\nThe lower module owns the interface; the higher module implements it and binds it in its service provider.\n\n``` php\n// app/Modules/Billing/Contracts/OrderTotals.php\nnamespace App\\Modules\\Billing\\Contracts;\n\ninterface OrderTotals\n{\n    public function forOrder(int $orderId): Money;\n}\n\n// app/Modules/Orders/Billing/EloquentOrderTotals.php\nfinal class EloquentOrderTotals implements \\App\\Modules\\Billing\\Contracts\\OrderTotals\n{\n    public function forOrder(int $orderId): Money\n    {\n        return Money::ofMinor(Order::findOrFail($orderId)->lines()->sum('total_minor'), 'USD');\n    }\n}\n\n// app/Modules/Orders/OrdersServiceProvider.php\n$this->app->bind(OrderTotals::class, EloquentOrderTotals::class);\n```\n\nBilling now depends only on its own interface. deptrac sees Orders → Billing, which is the allowed direction.\n\n```\n// Orders dispatches, knowing nothing about who listens\nOrderPlaced::dispatch($order->id, $order->tenant_id);\n\n// Billing listens, idempotently\nfinal class CreateInvoiceForOrder implements ShouldQueue\n{\n    public function handle(OrderPlaced $e): void\n    {\n        Invoice::firstOrCreate(['order_id' => $e->orderId], [...]);\n    }\n}\n```\n\nKeep 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.\n\nThe 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.\n\n```\n# .github/workflows/ci.yml (excerpt)\n- name: Module boundaries\n  run: vendor/bin/deptrac analyse --fail-on-uncovered --report-uncovered --no-progress\n```\n\nWith 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.\n\nIf your modular monolith has already tangled and you want a second pair of eyes, our [Laravel development](https://looporigin.com/services/laravel-development?utm_source=devto&utm_medium=series&utm_campaign=dependency-cycles-modular-laravel) page explains how we approach these refactors, and you can [contact us](https://looporigin.com/contact?utm_source=devto&utm_medium=series&utm_campaign=dependency-cycles-modular-laravel) with a short description of the modules involved.\n\nNo. 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.\n\nNo. 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.\n\nA 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.\n\nAs little as possible: value objects like `Money`, base exceptions and event classes. If Shared starts holding business logic, it becomes the new tangle.\n\nNot 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.\n\nOn 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.\n\nNext in this series, Part 3 covers upgrading old PHP versions safely with Rector and CI.", "url": "https://wpnews.pro/news/untangling-dependency-cycles-in-a-modular-laravel-monolith", "canonical_source": "https://dev.to/muhammadalimughal/untangling-dependency-cycles-in-a-modular-laravel-monolith-nl7", "published_at": "2026-11-20 16:29:37+00:00", "updated_at": "2026-11-20 16:44:39.295563+00:00", "lang": "en", "topics": ["developer-tools"], "entities": ["Loop Origin", "Laravel", "deptrac", "PHP"], "also_reported_by": [], "takeaway": "Run deptrac with a baseline formatter so CI fails only on newly introduced module dependencies, then break reverse edges with contracts for synchronous reads and domain events for reactions.", "recommendation": {"advice": "Add a deptrac ruleset over your modules and commit a baseline of current violations so CI blocks only new dependency cycles while you untangle existing ones.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/untangling-dependency-cycles-in-a-modular-laravel-monolith", "markdown": "https://wpnews.pro/news/untangling-dependency-cycles-in-a-modular-laravel-monolith.md", "text": "https://wpnews.pro/news/untangling-dependency-cycles-in-a-modular-laravel-monolith.txt", "jsonld": "https://wpnews.pro/news/untangling-dependency-cycles-in-a-modular-laravel-monolith.jsonld"}}