lead
Magento 2 module architecture is one of the better-documented subjects in the ecosystem and one of the worst-executed, and the gap between those two facts is not knowledge — it is that the documentation describes a greenfield module while the codebase in front of you is four years old, has a Helper\Data with two thousand lines in it, and ships revenue every week. Nobody gets to stop and rebuild. So this is the version that assumes you cannot: what a service contract has to look like to survive the WebAPI layer, why DTOs are the piece teams skip and then regret, the two generated classes that do most of the container’s real work, the contribution pattern that stops people writing plugins around your module, where package boundaries actually belong, and a phased strangler refactor that keeps the store shippable the entire time.
TL;DR — Split a feature into an Api package and everything else, before you need to. Magento core does exactly this — magento/module-inventory-api requires only php and magento/framework, and the Luma storefront package depends on the *-api packages, never on the implementation. Service contracts that hold, DTOs that survive the WebAPI layer and a strangler refactor that ships weekly all follow from that one property. The gap between how well this is documented and how badly it is executed is not knowledge.
baseline: what the monolith actually costs
The two conventions that cause the most avoidable pain, both invisible until they bite: fully-qualified class names in Api/ interface docblocks — Magento’s WebAPI layer reads those docblocks to build its type map, and use imports do not apply there — and Api/Data/*Interface setters returning the interface, not void. Get either wrong and the module works fine in PHP and breaks the moment it is exposed over REST.
A. The Monolith Problem
Most Magento projects start with a single theme + customizations folder:
app/
code/
local/
MyCompany/
CustomLogic/
Model/
Observer.php # Listens to everything
Helper.php # Static methods, god object
Block/
ProductList.php
Problems:
- Tight coupling: Observer depends on Payment, Shipping, Inventory (can’t change one without breaking others)
- Hard to test: Observer loads entire framework
- Difficult to reuse: Payment logic lives inside Observer; can’t use in CLI command
- Scaling pain: Multiple teams editing same files → merge conflicts
- Deployment risk: Any change could break unrelated features
B. The Modular Solution
Break into focused, self-contained modules:
app/
code/
MyCompany/
Inventory/
Api/
InventoryInterface.php
Data/
InventoryDataInterface.php
Model/
Inventory.php
Service/
StockService.php
etc/
di.xml
Payment/
Api/
PaymentProcessorInterface.php
Service/
PaymentService.php
etc/
di.xml
Shipping/
Api/
ShippingCalculatorInterface.php
Service/
ShippingService.php
etc/
di.xml
Benefits:
- Decoupling: Inventory module doesn’t care how Payment works
- Testability: Inject InventoryInterface mock in tests
- Reusability: StockService usable in CLI, REST API, admin, storefront
- Parallelization: Teams work independently
- Easy to replace: Swap ShippingService implementation without touching calling code
II. ServiceContract Pattern (The Foundation)
A. What a service contract actually is
A service contract is a pair: an interface under Api/ that states what the module does, and a DTO interface under Api/Data/ that states what it passes around. Everything else in the module — models, resource models, collections — becomes an implementation detail nobody outside the module is allowed to name.
Two properties make it worth the ceremony. Callers depend on a name that will not change when you rewrite the internals, and the interface is the only thing you have to keep stable across a major version. That is the whole contract, in both senses of the word.
<?php
declare(strict_types=1);
namespace MyCompany\Inventory\Api;
interface InventoryServiceInterface
{
/**
* Available quantity for a product in a given stock, reservations deducted.
*
* @param int $productId
* @param int $stockId
* @return int Units available to promise; never negative.
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getAvailableStock(int $productId, int $stockId): int;
/**
* Reserve stock against an order.
*
* @param int $productId
* @param int $qty Units to reserve; must be positive.
* @param int $orderId
* @return \MyCompany\Inventory\Api\Data\ReservationInterface
* @throws \Magento\Framework\Exception\LocalizedException When stock is insufficient.
*/
public function reserveStock(int $productId, int $qty, int $orderId): Data\ReservationInterface;
/**
* Release every reservation held by an order.
*
* @param int $orderId
* @return void
*/
public function releaseStock(int $orderId): void;
}
Three conventions in that snippet do real work and are easy to skip. declare(strict_types=1) on every file, so a string "5" arriving from a REST payload fails loudly instead of silently becoming 5. Fully-qualified class names in the @param/@return/@throws docblocks rather than short names, because Magento’s WebAPI layer reads those docblocks to build its own type map and use imports do not apply there — a short name in an Api/ interface is a bug waiting for the first REST call. And the units and invariants written down in prose ("never negative", "must be positive"), because the type system cannot carry them and the next reader will otherwise guess.
The implementation is unremarkable by design — classic typed properties, constructor assignment, no promotion, no readonly, so the class stays subclassable and the signature stays stable:
<?php
declare(strict_types=1);
namespace MyCompany\Inventory\Model;
use MyCompany\Inventory\Api\InventoryServiceInterface;
use MyCompany\Inventory\Api\InventoryRepositoryInterface;
use MyCompany\Inventory\Api\ReservationRepositoryInterface;
class InventoryService implements InventoryServiceInterface
{
/**
* @var \MyCompany\Inventory\Api\InventoryRepositoryInterface
*/
private $inventoryRepository;
/**
* @var \MyCompany\Inventory\Api\ReservationRepositoryInterface
*/
private $reservationRepository;
public function __construct(
InventoryRepositoryInterface $inventoryRepository,
ReservationRepositoryInterface $reservationRepository
) {
$this->inventoryRepository = $inventoryRepository;
$this->reservationRepository = $reservationRepository;
}
public function getAvailableStock(int $productId, int $stockId): int
{
$onHand = $this->inventoryRepository->get($productId, $stockId)->getQty();
$reserved = $this->reservationRepository->getReservedQty($productId, $stockId);
return max(0, $onHand - $reserved);
}
}
Note what the service does not do: no SQL, no getConnection(), no direct $model->save(). Persistence lives behind the two repositories, which is the layering rule that makes the rest of this article possible. A service that reaches into a resource model has silently become the monolith again, one method at a time.
DI registration (etc/di.xml):
<config>
<preference for="MyCompany\Inventory\Api\InventoryServiceInterface"
type="MyCompany\Inventory\Service\InventoryService" />
</config>
B. Why ServiceContract Matters
1. Decoupling: Calling code never imports InventoryService; only imports interface
2. Testability: Easy to mock:
$mockInventory = $this->createMock(InventoryServiceInterface::class);
$mockInventory->method('getAvailableStock')->willReturn(100);
3. Swappability: Swap implementation (e.g., remote warehouse API) without changing callers
4. Documentation: Interface is self-documenting (what methods, what they return, why)
C. ServiceContract vs Helper (Anti-Pattern)
❌ Old way (Helper):
// app/code/MyCompany/Inventory/Helper/Data.php
class Data extends \Magento\Framework\App\Helper\AbstractHelper {
public static function getStock($productId) { ... }
}
// Caller
$stock = MyCompany\Inventory\Helper\Data::getStock(123); // Static!
Problems:
- Static methods are hard to test (can’t mock)
- Helper lives in global scope (tight coupling)
- Interdependencies unclear
✅ New way (ServiceContract):
class CheckoutService {
public function __construct(InventoryServiceInterface $inventory) {
$this->inventory = $inventory; // Injected
}
public function validateOrder($orderId) {
$stock = $this->inventory->getAvailableStock($productId, $stockId);
}
}
Benefits:
- Dependency declared upfront (in constructor)
- Easy to test (mock inventory, test checkout in isolation)
- Clear what this service depends on
III. Data Transfer Objects (DTOs)
A. What is a DTO?
Data container with no business logic. Used to pass data across module boundaries.
Example: InventoryData
namespace MyCompany\Inventory\Api\Data;
interface InventoryDataInterface {
public function getProductId();
public function setProductId($productId);
public function getQty();
public function setQty($qty);
public function getWarehouseId();
public function setWarehouseId($warehouseId);
public function getReservedQty();
public function setReservedQty($reservedQty);
}
Implementation:
namespace MyCompany\Inventory\Model\Data;
class InventoryData extends \Magento\Framework\DataObject implements InventoryDataInterface {
public function getProductId() {
return $this->getData('product_id');
}
public function setProductId($productId) {
return $this->setData('product_id', $productId);
}
// ... other getters/setters
}
B. Why DTOs Matter
1. API Contract: REST endpoint returns DTO (consistent shape)
2. Type Safety: Type hints on DTO instead of array
3. Versioning: Can add new DTO fields without breaking old callers (they ignore unknown fields)
4. Testability: Easy to create test fixture:
$data = new InventoryData();
$data->setProductId(123)->setQty(100);
$this->inventory->reserveStock($data);
C. DI Registration for DTOs
<config>
<type name="MyCompany\Inventory\Model\Data\InventoryData">
<arguments>
<argument name="data" xsi:type="array">
<item name="product_id" xsi:type="string">0</item>
<item name="qty" xsi:type="string">0</item>
</argument>
</arguments>
</type>
</config>
IV. Dependency Injection Container & DI.xml
A. The Problem DI Solves
Without DI:
class OrderService {
public function createOrder($customerId) {
$inventory = new InventoryService(); // Hardcoded
$payment = new PaymentService(); // Hardcoded
$shipping = new ShippingService(); // Hardcoded
// ... create order
}
}
Problem: Can’t test (can’t inject mocks); changing PaymentService → must recompile all code
With DI:
class OrderService {
public function __construct(
InventoryServiceInterface $inventory,
PaymentServiceInterface $payment,
ShippingServiceInterface $shipping
) {
$this->inventory = $inventory;
$this->payment = $payment;
$this->shipping = $shipping;
}
}
Benefit: Magento’s DI container injects instances at runtime (can mock for tests)
B. DI.xml Structure
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!-- 1. Preferences: default implementation -->
<preference for="MyCompany\Inventory\Api\InventoryServiceInterface"
type="MyCompany\Inventory\Service\InventoryService" />
<!-- 2. Virtual types: lightweight service instances -->
<virtualType name="InventoryServiceReadOnly" type="MyCompany\Inventory\Service\InventoryService">
<arguments>
<argument name="readonly" xsi:type="boolean">true</argument>
</arguments>
</virtualType>
<!-- 3. Type configuration: constructor arguments -->
<type name="MyCompany\Inventory\Service\InventoryService">
<arguments>
<argument name="inventoryRepository" xsi:type="object">
MyCompany\Inventory\Model\ResourceModel\InventoryRepository
</argument>
<argument name="reservationRepository" xsi:type="object">
MyCompany\Inventory\Model\ResourceModel\ReservationRepository
</argument>
<argument name="logger" xsi:type="object">Psr\Log\LoggerInterface</argument>
</arguments>
</type>
</config>
C. Common DI Mistakes
❌ Wrong: Hardcoded dependency
class CheckoutService {
public function __construct() {
$this->inventory = new InventoryService(); // Can't test, can't swap
}
}
✅ Right: Injected dependency
class CheckoutService {
public function __construct(InventoryServiceInterface $inventory) {
$this->inventory = $inventory; // Testable, swappable
}
}
❌ Wrong: Service locator (anti-pattern)
class CheckoutService {
public function __construct(ObjectManager $om) {
$this->om = $om;
}
public function validate() {
$inventory = $this->om->create(InventoryService::class); // Hidden dependency!
}
}
✅ Right: Explicit injection
class CheckoutService {
public function __construct(InventoryServiceInterface $inventory) {
$this->inventory = $inventory;
}
}
D. Factory and Proxy: the two classes you never write
Magento’s DI container generates code, and two generated types do most of the work in a well-structured module. Both exist to solve problems constructor injection creates, and both are invisible in composer.json because nothing ships them — setup:di:compile writes them into generated/code/.
Factory — for things DI must not own. Constructor injection hands you one shared instance. That is right for services and wrong for entities: an order, a quote item, a DTO. You need a new one per call, with runtime arguments the container cannot know. Ask for SomethingFactory and Magento generates it:
<?php
declare(strict_types=1);
namespace MyCompany\Inventory\Model;
use MyCompany\Inventory\Api\Data\ReservationInterfaceFactory;
class ReservationBuilder
{
/**
* @var \MyCompany\Inventory\Api\Data\ReservationInterfaceFactory
*/
private $reservationFactory;
public function __construct(ReservationInterfaceFactory $reservationFactory)
{
$this->reservationFactory = $reservationFactory;
}
public function build(int $productId, int $qty): \MyCompany\Inventory\Api\Data\ReservationInterface
{
return $this->reservationFactory->create([
'data' => ['product_id' => $productId, 'qty' => $qty],
]);
}
}
There is no ReservationInterfaceFactory.php anywhere in the module. Suffix an existing type with Factory, inject it, and the compiler writes the class. Note it works on the interface — the generated factory resolves the preference, so callers still never name a concrete class.
The rule that follows: inject a service, factory an entity. A constructor argument that is a model, a DTO or anything with per-request state is a design error; a factory of that thing is correct.
Proxy — for expensive dependencies you usually do not touch. Constructor injection is eager. Every dependency of every dependency is instantiated before your method runs, and one heavy object at the bottom of the graph — a session, an HTTP client, a config reader that parses XML — is paid for on every request that constructs the branch, including requests that never call it.
A Proxy is a generated subclass with the same public API that constructs the real object on first method call. You do not inject it in PHP; you swap it in di.xml, which means the class under it stays honest about what it depends on:
<type name="MyCompany\Inventory\Model\StockNotifier">
<arguments>
<argument name="mailer" xsi:type="object">MyCompany\Mail\Model\Mailer\Proxy</argument>
</arguments>
</type>
Core does exactly this. Magento\Catalog\Helper\Product takes Magento\Catalog\Model\Session\Proxy rather than the session itself, because most product-helper calls never touch session state and starting a session is not free.
Where proxies go wrong. They are a performance tool, not a design tool, and reaching for one to break a circular dependency hides the cycle instead of fixing it. If class A needs B and B needs A, a proxy makes the container stop complaining and leaves you with two classes that are one class. Split the shared concern out instead. The legitimate use is narrow: a genuinely expensive object, genuinely rarely used on that path, measured rather than assumed.
E. The contribution pattern: letting other modules extend yours without touching it
This is the mechanism that makes a Magento module extensible by strangers, and it is the piece most home-grown modules never build.
The shape: your module declares an interface and a composite that holds an array of implementations of that interface. It injects nothing concrete. Any other module — yours, a third party’s, a client’s project code — contributes an implementation by adding an array item in its own di.xml. Nothing in your module changes, and nothing in the contributing module needs your permission.
Magento core does this everywhere. Magento\Framework\Url\ModifierComposite is the pattern at its smallest:
class ModifierComposite implements ModifierInterface
{
/**
* @var ModifierInterface[]
*/
private $modifiers;
/**
* @param ModifierInterface[] $modifiers
*/
public function __construct(array $modifiers = [])
{
$this->modifiers = $modifiers;
}
public function execute($url, $mode = ModifierInterface::MODE_ENTIRE)
{
foreach ($this->modifiers as $modifier) {
$url = $modifier->execute($url, $mode);
}
return $url;
}
}
An empty default, an array of the interface, a loop. That is the whole class.
Your module wires the composite as the preference, so everyone who injects the interface gets the aggregate:
<!-- MyCompany_Inventory: etc/di.xml -->
<preference for="MyCompany\Inventory\Api\StockValidatorInterface"
type="MyCompany\Inventory\Model\StockValidator\Composite"/>
And any dependent module contributes without editing a line of yours:
<!-- ClientProject_Warehouse: etc/di.xml -->
<type name="MyCompany\Inventory\Model\StockValidator\Composite">
<arguments>
<argument name="validators" xsi:type="array">
<item name="hazmat" xsi:type="object" sortOrder="20">
ClientProject\Warehouse\Model\Validator\HazmatValidator
</item>
</argument>
</arguments>
</type>
Because di.xml files merge across modules, the arrays merge too. Three modules can each add a validator and none of them knows the others exist. That holds as long as the array is declared in a module’s own di.xml; there is one place it does not, covered below.
Four things separate a contribution point that survives from one that becomes a support burden:
Name the items. <item name="hazmat"> is a key, not decoration. A later module can override that exact validator by reusing the name, or disable it by setting the item to null — impossible with a positional array.
Order explicitly. Merge order across modules follows module load order, which is a function of <sequence> declarations and therefore not something a contributor controls. If order matters, take sortOrder per item and sort in the constructor. Magento\Framework\ObjectManager\Helper\Composite::filterAndSortDeclaredComponents() exists precisely for this, and it also drops misconfigured entries rather than fataling at runtime.
Validate the contribution. array $validators = [] promises nothing. A contributor typos a class name and you get a fatal deep inside a loop, in their module’s name, blamed on yours. Check in the constructor and throw with the offending key:
public function __construct(array $validators = [])
{
foreach ($validators as $name => $validator) {
if (!$validator instanceof StockValidatorInterface) {
throw new \InvalidArgumentException(
sprintf('Stock validator "%s" must implement %s.', $name, StockValidatorInterface::class)
);
}
}
$this->validators = $validators;
}
Treat the interface as published API. The moment someone contributes to your composite, that interface is a contract with a codebase you cannot see. It belongs under Api/, it changes on major versions only, and adding a method to it is a breaking change even though PHP will let you do it quietly.
The merge only holds inside one configuration stage. Magento loads DI configuration in three of them: initial (app/etc/di.xml), global (<module>/etc/di.xml), then area-specific (<module>/etc/<area>/di.xml). Arrays with the same name merge within a stage — which is exactly why the pattern above works between modules, since they all sit in the global one. Across stages they do not merge. Adobe’s own reference is explicit: "When the application loads a new configuration at a later time, either by a more specific scope or through code, then any array definitions in the new configuration will replace the loaded config instead of merging."
So a composite whose array is declared in a module’s di.xml behaves as described above. A composite whose array is declared in the root app/etc/di.xml does the opposite: your contribution replaces core’s entries wholesale instead of joining them. Core ships at least one of these on a hot path. Magento\Framework\Webapi\Rest\Request\DeserializerFactory‘s deserializers array — the map from Content-Type to request decoder — lives in the root file. Add a single item for your own format from a module di.xml and every existing POST/PUT against the REST API begins failing site-wide with Server cannot understand Content-Type HTTP header media type application/json: an error that reads like the client sent a bad header, and points nowhere near the DI array that was just clobbered.
Magento confirmed the behaviour and did not change it. Issue #26433 was triaged Severity S1, answered with "it’s a known behavior of the configuration merge process … the common solution in this case is to duplicate original arguments and add the new ones", and closed in September 2021 by the reporter rather than by a fix — "over a year without any solution and no possible fix from the CORE team". The general form of it, array arguments replaced rather than merged when they come from different areas, is issue #34464 and is still open. What the report did produce was a documentation warning (devdocs PR #8180), which is the sentence quoted above.
Moving your declaration into the area that actually uses it — etc/webapi_rest/di.xml for the REST case — is the obvious way to dodge the duplication, and it does not work. Measured on 2.4.8-p5 with a single-item array, the global stage and the webapi_rest area stage behave identically: the array is replaced either way. A later stage is later, not safer, and only the initial stage merges with the initial stage — which a module cannot ship.
The working rule when contributing to an array you do not own: find where the argument is declared before adding to it. Declared in a module di.xml — contribute normally. Declared in the root app/etc/di.xml — redeclare every existing entry alongside your own, and write a test that fails when core adds one more, because nothing else will tell you.
The payoff is the inversion this whole article is about, applied at runtime: your module stops needing to know its extensions, and extension stops requiring a plugin around your code. A plugin is what you write when a module gave you no contribution point. A composite is how you avoid being the module people write plugins around.
V. Module Boundaries & Dependency Graph
A. The Dependency Rule
A module can depend on modules that are less complex than it.
Typical hierarchy (complexity bottom-up):
App (highest complexity)
│
├─ Checkout
│ ├─ Order
│ ├─ Inventory
│ ├─ Payment
│ └─ Shipping
│
└─ Catalog (mid complexity)
├─ Product
└─ Category
└─ Eav (low complexity)
Rule: Checkout can depend on Inventory, Payment, Shipping
Forbidden: Inventory cannot depend on Checkout (circular dependency!)
B. Detecting Bad Dependencies (Circular Imports)
Magento provides a command:
bin/magento dev:di:dependencies-violations
Output example:
Errors:
MyCompany\Checkout\Service\OrderService depends on MyCompany\Inventory\Service\InventoryService
MyCompany\Inventory\Service\InventoryService depends on MyCompany\Checkout\Service\OrderService
^ CIRCULAR DEPENDENCY!
How to fix circular dependencies:
1. Extract shared logic into a third module (lower-level)
2. Use events (loosely-coupled)
3. Use plugin interceptors (aspect-oriented)
C. Event-Driven Architecture (Decoupling)
Instead of Inventory calling Checkout directly (circular):
// InventoryService publishes event
$this->eventManager->dispatch('inventory_stock_changed', [
'product_id' => $productId,
'qty' => $newQty
]);
// CheckoutService listens
class CheckoutObserver implements \Magento\Framework\Event\ObserverInterface {
public function execute(\Magento\Framework\Event\Observer $observer) {
$productId = $observer->getEvent()->getProductId();
// Re-validate orders containing this product
}
}
Benefit: Inventory doesn’t know Checkout exists; no circular dependency
VI. One feature, several Composer packages
Everything so far treats "module" as one directory and one Composer package. For a feature of any size that is the wrong unit, and Magento core stopped using it years ago.
A. What core actually does
Multi-Source Inventory is the reference implementation. One feature, split across dozens of packages:
magento/module-inventory-api contracts only
magento/module-inventory business logic
magento/module-inventory-indexer indexing concern
magento/module-inventory-cache caching concern
magento/module-inventory-admin-ui Adminhtml
magento/module-inventory-catalog-frontend-ui Luma storefront
magento/module-inventory-graph-ql GraphQL surface
magento/module-inventory-in-store-pickup-webapi-extension REST surface
The dependency directions are the interesting part. module-inventory-api requires exactly two things — php and magento/framework. It knows nothing about inventory implementation, admin UI, GraphQL or the storefront. And module-inventory-catalog-frontend-ui, the Luma-facing package, requires module-inventory-sales-api and module-inventory-configuration-api — the contract packages, never the implementation.
That is not tidiness. It is what makes the storefront package removable.
B. The layout, and what goes in each package
Vendor_FooApi Api/*Interface, Api/Data/*Interface, public constants,
enums, exception types. No logic. Depends on framework only.
Vendor_Foo Model/, ResourceModel/, the service implementations,
preferences that bind Api interfaces to them, schema.
Vendor_FooAdminUi Controller/Adminhtml/, ui_component/, system.xml, acl.xml,
Adminhtml layout and templates.
Vendor_FooFrontendUi Luma-facing blocks, phtml, layout XML, view models.
Vendor_FooGraphQl Model/Resolver/, schema.graphqls.
Vendor_FooWebapi etc/webapi.xml and any REST-specific DTO shaping.
Which artefact lives where is decided by one question: who needs to compile against it?
- An interface consumed by another package goes in
Api. An interface used only inside the implementation stays with the implementation — putting it inApipublishes a contract you did not mean to publish. - A constant is a contract the moment anything outside the package reads it.
SomeProcessor::CODE, referenced from adi.xmlin another module viaxsi:type="const", is public API. Core does this constantly —Magento\Catalog\Model\Indexer\Category\Product::INDEXER_IDis read from other modules’di.xml. Constants like that belong in theApipackage, or on an interface there. - A DTO implementation goes in the implementation package; its interface goes in
Api. Callers type-hint the interface and build via the generated factory, so nothing outside ever names the concrete class. - Exceptions thrown across a package boundary are part of the contract. If
Apideclares@throws, the exception type belongs inApi. di.xmlpreferences belong in the implementation package, never inApi. A contracts package that binds its own preference cannot be reimplemented, which defeats its purpose.
The test for whether you split correctly: can you composer remove Vendor_FooFrontendUi and still have a working admin and a working API? If removing the storefront breaks order placement, the boundary is decorative.
C. Where this pattern comes from, and why the parallel is exact
Anyone who worked in J2EE will recognise this immediately, because it is the same layout with different filenames. A Maven multi-module enterprise project splits one feature into:
foo-api interfaces, DTOs, exceptions — the only jar others compile against
foo-core EJBs / CDI beans, the business logic
foo-web the JSF or servlet tier
foo-rest JAX-RS resources
foo-ear assembly
The rule there was the rule here: only the API jar is on anyone else’s compile path. foo-web compiles against foo-api and never against foo-core. Teams did that for one reason above all others — so the presentation tier could be replaced without touching business logic. When JSF gave way to a React SPA calling REST, foo-web was deleted and foo-rest grew. foo-api and foo-core did not change, because nothing in them ever knew a JSF page existed.
Magento has exactly that decision in front of it, and it is not hypothetical. Luma is the legacy presentation tier. Hyvä, a React storefront on GraphQL, or a headless PWA are the replacements, and stores are making that move now. If your feature is one package with Block/, view/frontend/templates/, Model/ and Api/ in it, migrating the storefront means opening every file in the module and hoping. If it is split the way MSI is split, migration is:
composer remove vendor/module-foo-frontend-ui # Luma tier drops out
composer require vendor/module-foo-hyva-ui # new tier, same contracts
Vendor_FooApi and Vendor_Foo are untouched, because neither ever knew what a .phtml was. That is the entire return on the split, and it arrives years after you paid for it — which is precisely why it gets skipped.
D. The honest cost
This is real overhead and pretending otherwise is how teams get talked into it and then resent it. Six packages means six composer.json files, six registration.php files, six sets of <sequence> declarations, six repositories or one monorepo with subtree splits, and a release process where a change to Api means coordinating versions across everything that depends on it. Cross-package refactoring that an IDE would do in one move now spans repos.
Where it is worth it:
- The feature has a realistic prospect of a presentation-tier swap — which, for any Magento store not already on Hyvä, is most of them.
- The feature is consumed by more than one surface: admin plus storefront plus API. Two surfaces is the threshold; one surface does not justify it.
- The feature is sold or shared across projects, so someone else’s code depends on your contracts and you need a stable thing to version.
Where it is not:
- A single-surface module. An admin-only report does not need an
Apipackage. - A module with no second consumer. The rule from earlier in this article holds here too: an abstraction you cannot name two call sites for is speculation. Two packages you cannot name two consumers for is the same mistake with more
composer.json.
The pragmatic middle, and what most projects should do: start with Vendor_FooApi and Vendor_Foo — contracts separated from implementation, two packages, low overhead. Split the UI tiers out at the moment a second surface appears or a storefront migration becomes real, not before. The Api split is the one that is expensive to retrofit, because it is the one everybody’s use statements point at; the UI split can be done later with mechanical moves.
working_example: strangling the monolith in three phases
A. Phase 1: Analysis (1–2 weeks)
1. Draw current dependency graph
2. Identify natural seams (where coupling is weakest)
3. List which teams will own which modules
Example seam: Shipping calculations are independent (could be own module)
B. Phase 2: Extract First Module (2–4 weeks)
Choose the simplest, most independent module to extract first.
Example: Extract Shipping into own module
1. Create app/code/MyCompany/Shipping/
2. Move shipping-related classes there
3. Create Api/ShippingCalculatorInterface.php
4. Implement Service/ShippingCalculator.php
5. Register in etc/di.xml
6. Remove shipping classes from theme/local
7. Update all callers to use new interface
8. Write tests (verify mock injection works)
9. Deploy and monitor
C. Phase 3: Repeat for Other Domains (2–4 weeks each)
Extract:
- Inventory (stock management)
- Payment (payment processing)
- Order (order orchestration)
D. Timeline for Medium Store
Week 1–2: Analysis + dependency audit
Week 3–6: Extract Shipping module
Week 7–10: Extract Inventory module
Week 11–14: Extract Payment module
Week 15–18: Extract Order orchestration module
Week 19–20: Clean up remaining code, integration tests
Total: 5 months for 10–15 person team
VIII. API Layer (REST/GraphQL on Top of Services)
A. REST Controller Pattern
namespace MyCompany\Inventory\Api;
class InventoryController implements \Magento\Framework\Webapi\Rest\Request\DeserializerInterface {
public function __construct(InventoryServiceInterface $inventoryService) {
$this->inventoryService = $inventoryService;
}
/**
* GET /V1/inventory/stock/:productId
* @param int $productId
* @return InventoryDataInterface
*/
public function get($productId) {
return $this->inventoryService->getStock($productId);
}
/**
* POST /V1/inventory/reserve
* @param InventoryDataInterface $inventory
* @return bool
*/
public function reserve($inventory) {
return $this->inventoryService->reserveStock(
$inventory->getProductId(),
$inventory->getQty(),
$inventory->getOrderId()
);
}
}
webapi.xml registration:
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<route url="/V1/inventory/stock/:productId" method="GET">
<service class="MyCompany\Inventory\Api\InventoryController" method="get" />
<resources>
<resource ref="Magento_Catalog::products"/>
</resources>
</route>
<route url="/V1/inventory/reserve" method="POST">
<service class="MyCompany\Inventory\Api\InventoryController" method="reserve" />
<resources>
<resource ref="Magento_Sales::orders"/>
</resources>
</route>
</routes>
B. Service vs Controller (Separation of Concerns)
- Service: Pure business logic (InventoryService)
- No HTTP awareness
- No request/response objects
- Testable in isolation
- Controller: HTTP layer (InventoryController)
- Handles request parsing
- Calls service
- Formats response
- Handles errors → HTTP status codes
Example:
// Service (pure logic)
public function reserveStock($productId, $qty, $orderId) {
if ($this->getAvailableStock($productId) < $qty) {
throw new InsufficientStockException("Not enough stock");
}
$this->reservationRepository->create($productId, $qty, $orderId);
}
// Controller (HTTP layer)
public function reserve($inventory) {
try {
$this->inventoryService->reserveStock(...);
return ['success' => true];
} catch (InsufficientStockException $e) {
throw new \Magento\Framework\Webapi\Exception(
__($e->getMessage()),
0,
\Magento\Framework\Webapi\Exception::HTTP_CONFLICT
);
}
}
IX. Testing & Isolation
A. Unit Test (Service In Isolation)
class InventoryServiceTest extends \PHPUnit\Framework\TestCase {
private $inventoryService;
private $inventoryRepository;
private $reservationRepository;
protected function setUp(): void {
$this->inventoryRepository = $this->createMock(InventoryRepository::class);
$this->reservationRepository = $this->createMock(ReservationRepository::class);
$this->inventoryService = new InventoryService(
$this->inventoryRepository,
$this->reservationRepository
);
}
public function testReserveStockSuccess() {
$this->inventoryRepository->method('get')
->willReturn((new InventoryData())->setQty(100));
$this->reservationRepository->method('getReservedQty')
->willReturn(0);
$result = $this->inventoryService->reserveStock(1, 50, 123);
$this->assertTrue($result);
}
public function testReserveStockInsufficientStock() {
$this->inventoryRepository->method('get')
->willReturn((new InventoryData())->setQty(10));
$this->expectException(InsufficientStockException::class);
$this->inventoryService->reserveStock(1, 50, 123);
}
}
Benefits:
- Fast (no DB, no HTTP)
- Deterministic (no external dependencies)
- Easy to write (just mock 2 dependencies)
B. Integration Test (Multiple Modules)
class CheckoutIntegrationTest extends \PHPUnit\Framework\TestCase {
private $checkoutService;
private $inventoryService;
private $paymentService;
protected function setUp(): void {
// Use real implementations (via DI container)
$this->checkoutService = ObjectManager::getInstance()->create(CheckoutService::class);
$this->inventoryService = ObjectManager::getInstance()->create(InventoryServiceInterface::class);
$this->paymentService = ObjectManager::getInstance()->create(PaymentServiceInterface::class);
}
public function testCheckoutFlow() {
// 1. Reserve inventory
$this->inventoryService->reserveStock(1, 1, null);
// 2. Process payment
$paymentResult = $this->paymentService->process(100.00, 'visa');
// 3. Create order
$order = $this->checkoutService->createOrder(123, 1, 1, $paymentResult['transactionId']);
$this->assertNotNull($order->getId());
$this->assertEquals('pending', $order->getStatus());
}
}
X. Module Communication Patterns
A. Synchronous (Blocking)
// Service A calls Service B directly
class OrderService {
public function __construct(PaymentServiceInterface $payment) {
$this->payment = $payment;
}
public function createOrder($customerId, $items) {
$result = $this->payment->process($total); // Blocks until done
if ($result['status'] != 'success') {
throw new PaymentFailedException();
}
// Create order...
}
}
Pros: Simple, immediate feedback
Cons: Tight coupling, if Payment is slow → Order is slow
B. Asynchronous (Non-Blocking)
// Service A publishes event
class OrderService {
public function __construct(EventManager $eventManager) {
$this->eventManager = $eventManager;
}
public function createOrder($customerId, $items) {
// Create order immediately (no payment block)
$order = $this->orderRepository->save($order);
// Publish event for async processing
$this->eventManager->dispatch('order_created', [
'order_id' => $order->getId(),
'total' => $order->getGrandTotal()
]);
return $order;
}
}
// Payment module listens
class OrderCreatedObserver implements ObserverInterface {
public function execute(Observer $observer) {
$order = $observer->getEvent()->getOrder();
$this->paymentService->process($order->getGrandTotal());
}
}
Pros: Decoupled, fast order creation, failures isolated
Cons: Harder to debug, no immediate feedback
C. When to Use Each
- Sync: Checkout flow (need payment result before order completes)
- Async: Notifications (email, SMS; doesn’t block order)
- Async: Long-running jobs (image optimization, reporting)
tradeoff: when modularising is the wrong call
A. Oversplitting (Too Many Tiny Modules)
❌ Bad:
MyCompany/
Price/ # Just price calc
Tax/ # Just tax calc
Discount/ # Just discount
Stock/ # Just inventory
Problem: Each module has 1–2 classes; overhead outweighs benefit
✅ Good:
MyCompany/
Pricing/ # Price + Tax + Discount (related)
Inventory/ # Stock management
Order/ # Order logic
Principle: Module = cohesive domain, not individual class
B. Premature Extraction
❌ Bad: Extract module before it’s proven
// Haven't even used this 5 times yet, extracting anyway
MyCompany/
FutureThing/
Service/
FutureThingService.php
✅ Better: Extract when pain is clear
// Used shipping calc in 5 places, merge conflicts, time to extract
MyCompany/
Shipping/
Service/
ShippingCalculator.php
Principle: Extract when you have concrete evidence (not "might need it")
C. Over-Interfacing
❌ Bad:
interface ProductInterface { }
interface InventoryInterface { }
interface PriceInterface { }
// ... for every class
Cost: Maintenance burden, file bloat
Benefit: Might swap implementations (do you really?)
✅ Better: Interface only where you’ll actually swap
// PaymentProcessorInterface: YES (will integrate Stripe, PayPal, etc.)
interface PaymentProcessorInterface { }
// InventoryDataObject: NO (not swapping this)
class InventoryData { }
XII. Metrics & Success Criteria
A. How to Know Refactoring is Working
1. Shorter feedback loops: Tests run in <5 min (not 30 min)
2. Fewer merge conflicts: Teams work in separate modules
3. Easier onboarding: New dev can understand 1 module in 2 days (not whole codebase)
4. Faster deployments: Can deploy Shipping independently (not whole app)
5. Fewer bugs: Changes isolated to module; unrelated features not affected
B. Anti-Metrics (Signs of Bad Architecture)
- Tests take >15 min to run
- Every change affects 5+ files
- New feature requires modifying 3+ modules
- Circular dependencies (di:dependencies-violations fails)
- Large monolithic Observer that listens to everything
XIII. Real-World Case Study
Store: Medium fashion retailer, 15k SKU, 50k orders/month, 5-person dev team
Before (Monolith):
- 1 theme + local customizations folder
- Shipping, Payment, Inventory all hardcoded into Observer
- Unit tests: 12 (all integration tests, slow)
- Deployment: 45 min (rebuild everything)
- Merge conflicts: 2–3 per day (theme/local folder chaos)
Refactoring (5 months):
- Extracted Shipping module (1 month)
- Extracted Inventory module (1.5 months)
- Extracted Payment module (1.5 months)
- Extracted Order orchestration (1 month)
After (Modular):
- 4 independent modules + core orchestration
- Each module <500 lines; clear interfaces
- Unit tests: 150 (fast, isolated)
- Deployment: 10 min (only changed modules)
- Merge conflicts: <1 per week
- Time to add feature: 30% faster (clear where code goes)
ROI:
- Reduced bugs by ~40% (fewer side effects)
- Reduced deployment risk (smaller, isolated changes)
- Team parallelization (4 devs can work independently)
- Payback: 2 months (less rework on bug fixes)
verification: the before-and-after checklist
Four checks specific to the material above, before the general list:
- [ ] No entity is constructor-injected. Every model, DTO or per-request object arrives via a generated
*Factory. A service in a constructor is right; a quote item is not. - [ ] Every
Proxyhas a measurement behind it. If it was added to silence a circular-dependency error rather than to defer a genuinely expensive object, the cycle is still there and still yours. - [ ] Every composite validates and names its contributions. Items keyed by name,
sortOrderhonoured if order matters, and a constructor check that throws with the offending key rather than fataling inside the loop. - [ ]
composer remove <the frontend package>leaves a working admin and API. If it does not, the package split is decorative and will not survive a storefront migration.
Before Refactoring
- [ ] Document current architecture (draw dependency graph)
- [ ] Identify natural module boundaries
- [ ] Count existing tests + code coverage
- [ ] Measure deployment time + frequency
- [ ] Count merge conflicts per week
During Refactoring
- [ ] Create ServiceContract (interface)
- [ ] Implement Service
- [ ] Register in di.xml
- [ ] Update all callers (use interface, not concrete class)
- [ ] Write unit tests (mock dependencies)
- [ ] Add integration tests
- [ ] Test on staging (same data as production)
- [ ] Deploy (monitor errors for 2 hours)
After Refactoring
- [ ] Re-measure: test time, deployment time, merge conflicts
- [ ] Calculate ROI (time saved vs refactoring cost)
- [ ] Document module (API, common use cases)
- [ ] Schedule team training (how to use new modules)
- [ ] Plan next module extraction
Related reading
- Magento 2 Testing in CI/CD — the payoff; untestable code is nearly always a boundary problem, not a tooling problem.
- Stop Rebuilding Magento Features That Already Exist — the cheapest module is the one you did not write.
- When to Ship vs Build It Right in Magento 2 — how much architecture this particular ticket deserves.
- Magento 2 Entity Services: EAV Attribute Builder — service contracts applied to attribute management.
- Magento 2 REST API Gaps — what the API layer in Section VII can and cannot express.
- Magento REST API Content Negotiation: XML, Bulk, and YAML — the
app/etc/di.xmlarray-replacement trap above, hit in production and documented end to end. - Magento Root Cause Analysis: Five Whys That Stick — three of its four failure shapes are boundary violations wearing a costume.
Sources & References
- Adobe Commerce: service contracts — the
Api/andApi/Data/conventions this article builds on. - Adobe Commerce: dependency injection —
di.xml, preferences, virtual types and argument replacement. - Adobe Commerce: module dependencies and
sequence— load order, and why two modules writing the same entity need one. - Adobe Commerce: proxies and factories — the two generated classes in Section IV.D.
Magento\Framework\Url\ModifierCompositeandMagento\Framework\ObjectManager\Helper\Composite— the contribution pattern in Section IV.E, as core implements it. Read them invendor/; they are about thirty lines each.- Multi-Source Inventory on GitHub — the reference multi-package feature.
composer.jsonofmodule-inventory-apiversusmodule-inventory-catalog-frontend-uishows the dependency direction that makes the split worth having. - Maven: guide to working with multiple modules — the J2EE lineage of the same layout, for readers who met it there first.
- Adobe Commerce: PHP coding standard — the baseline the snippets here follow.
- Martin Fowler, StranglerFigApplication — the incremental-replacement pattern behind the three-phase refactor.
Disclaimer
The case study timeline is a composite from refactors of comparable size, not a single audited engagement; the phase ordering transfers, the calendar does not. Snippets are illustrative and omit the licence header every real file in this house style carries. And the honest caveat on the whole subject: a module boundary you cannot name a second consumer for is speculation — the pattern is only worth its cost where two callers already exist.
