PHP Module Boundaries: Why Folders and Dependency Declarations Are Not Enough
DEV Community

PHP Module Boundaries: Why Folders and Dependency Declarations Are Not Enough

Coretsia Engineering Notes - 02

In the first Engineering Note, I explored an important distinction: a deterministic dependency order can still be incorrect. A similar distinction exists in modular architecture.

A project can have well-organized directories, separate Composer packages, and explicit dependency declarations. Its code can pass functional tests, yet one package may still reach into another package's internals or depend on a package it never declared.

The question is not merely whether the application runs, but whether the relationships between its components are the ones the architecture intended. This article demonstrates that distinction with a small PHP 8.4 experiment. No particular application framework is required.

The illusion of modularity

Moving classes into directories named Catalog, Billing and Shipping is a reasonable starting point, but the filesystem does not decide which classes can reference one another. PHP namespaces distinguish names; they are not package-level visibility modifiers. A public class remains accessible to other code if it can be loaded.

Marking a namespace or class as internal communicates an architectural intention, but PHP itself does not turn that intention into an access restriction. Composer solves a different problem. Its package requirements describe dependencies and version constraints for installation. PSR-4 autoloading maps names to files. Neither operation is, by itself, a rule about which reachable classes a particular package is permitted to consume.

Consider three distinct questions:

  • Directory and namespace structure - Who owns this code?
  • Package manifest - What must be installed for this package?
  • Architecture policy - Which source dependencies and API references are permitted?

These mechanisms complement one another. The mistake is treating one as a substitute for the others.

A minimal experiment

The example contains three local Composer packages:

packages/
  catalog/
    composer.json
    src/Contracts/PriceReaderInterface.php
    src/Internal/PriceCalculator.php
  billing/
    composer.json
    src/InvoiceService.php
  shipping/
    composer.json
    src/ShippingService.php

Initially, the declared package relationships are:

Shipping -> Billing -> Catalog

The arrow means that the source package directly requires the target package. It does not mean the reverse, and it does not silently grant permission to traverse the graph.

We define a small public API. Catalog exports PriceReaderInterface; PriceCalculator is an implementation detail. Billing exports InvoiceService. Shipping may consume Billing's public API and may consume Catalog's public API only if Shipping explicitly declares Catalog. Catalog must not depend on either higher-level package.

For reproducibility, all example packages have version 1.0.0. The complete manual setup is in the appendix; the automated reproduction uses independent Composer roots for five variants.

Catalog's public contract is intentionally small:

<?php declare(strict_types = 1);
namespace Acme\Catalog\Contracts;
interface PriceReaderInterface {
  public function priceCents(string $sku): int;
}

The synthetic implementation is a normal PHP class:

<?php declare(strict_types = 1);
namespace Acme\Catalog\Internal;
use Acme\Catalog\Contracts\PriceReaderInterface;
/** @internal */
final class PriceCalculator implements PriceReaderInterface {
  public function priceCents(string $sku): int {
    return 1200;
  }
}

The fixed value is intentional. We are testing architectural relationships, not pricing logic. Keeping the business result constant lets us compare two independent properties: execution and architecture compliance.

Experiment 1: crossing a public API boundary

Billing declares Catalog as a direct Composer dependency. That declaration is valid. Its source, however, can choose to couple itself to the concrete implementation:

<?php declare(strict_types = 1);
namespace Acme\Billing;
use Acme\Catalog\Internal\PriceCalculator;
final readonly class InvoiceService {
  public function __construct(private PriceCalculator $prices) {
  }
  public function totalCents(string $sku): int {
    return $this->prices->priceCents($sku);
  }
}

This is not just an unused import. PriceCalculator appears in the constructor signature and is used to calculate a result. Composer makes the class available, PHP accepts the type, and an application can inject a valid instance.

Billing is now coupled to a concrete implementation that belongs to Catalog. Renaming that class, changing how it is constructed, or replacing it with another implementation may force Billing to change even when Catalog's public contract is unchanged. That is a source-level architectural violation, not necessarily a runtime error.

The contract-based version makes the dependency explicit at the correct boundary:

<?php declare(strict_types = 1);
namespace Acme\Billing;
use Acme\Catalog\Contracts\PriceReaderInterface;
final readonly class InvoiceService {
  public function __construct(private PriceReaderInterface $prices) {
  }
  public function totalCents(string $sku): int {
    return $this->prices->priceCents($sku);
  }
}

The application composition root can still construct PriceCalculator and inject it. It is deliberately outside the analysed package sources and trusted to wire implementations in this fixture. The implementation is no longer a requirement of Billing's public constructor. In a real application, a factory or dependency-injection configuration could own the same decision under its own policy. The behavior has not changed; the ownership and coupling have.

Experiment 2: the undeclared dependency

The second problem is different. Suppose Shipping adds a direct reference to Catalog's public interface, while its own manifest still requires only Billing.

<?php declare(strict_types = 1);
namespace Acme\Shipping;
use Acme\Billing\InvoiceService;
use Acme\Catalog\Contracts\PriceReaderInterface;
final readonly class ShippingService {
  public function __construct(
    private InvoiceService $billing,
    private PriceReaderInterface $prices,
  ) {
  }
  public function totalCents(string $sku): int {
    $invoice = $this->billing->totalCents($sku);
    $base = $this->prices->priceCents($sku);
    return $invoice + intdiv($base, 4);
  }
}

Unlike the previous experiment, the referenced API is public. The problem is that the source relationship is not declared by its owner. The root consumer requires Shipping, which requires Billing, while Billing requires Catalog. Composer therefore installs Catalog transitively, and the autoloader can resolve PriceReaderInterface even though Shipping does not directly declare Catalog.

Shipping -> Billing -> Catalog
Shipping - - - - - -> Catalog (actual, undeclared)

That availability depends on Billing's current dependency graph. If Billing later changes its implementation and no longer requires Catalog, Shipping can lose a dependency that its own manifest never requested. Even when the graph does not change, the declaration misrepresents the package's actual needs.

The correction is to declare Catalog as a direct Composer dependency of Shipping. Its updated require section becomes:

"require": {
  "php": "~8.4.0",
  "acme/billing": "1.0.0",
  "acme/catalog": "1.0.0"
}

This correction is valid only because the architecture policy also permits that direction and the target is public. Adding a requirement should never be an automatic way to authorize a forbidden dependency.

Experiment 3: make the rules executable

To detect both problems automatically, we need an analysis step that checks real source references against an explicit policy. Deptrac supports grouping PHP classes into architecture layers and controlling the allowed dependencies between those layers. The experiment uses Deptrac 4.7.2 as a development tool.

We use four non-overlapping layers:

  • catalog_api: Catalog's Contracts namespace;
  • catalog_internal: Catalog's Internal namespace;
  • billing_api: Billing's source namespace in this small fixture;
  • shipping_api: Shipping's source namespace.

The baseline rules are:

ruleset:
  billing_api: [catalog_api]
  catalog_api: []
  catalog_internal: [catalog_api]
  shipping_api: [billing_api]

Catalog's implementation may implement its own contract. Billing may use Catalog's public layer, not Catalog's internal layer. Shipping may use Billing. Shipping's direct access to Catalog remains forbidden until its own manifest declares the relationship and the policy permits it.

The companion automation generates these rules from direct package requirements and an independent allowed-direction policy. It does not calculate the transitive closure. In the fixed variant, Shipping's rule becomes:

shipping_api: [billing_api, catalog_api]

The distinction matters: if we simply allowed every class in every installed package, our architecture check would recreate the original problem. Likewise, allowing an entire dependency package as one layer would not distinguish its public contracts from its internal classes. A static rule must operate at the same granularity as the architecture it claims to enforce.

Verification: runtime and architecture are separate outcomes

The baseline ShippingService only uses Billing:

<?php declare(strict_types = 1);
namespace Acme\Shipping;
use Acme\Billing\InvoiceService;
final readonly class ShippingService {
  public function __construct(private InvoiceService $billing) {
  }
  public function totalCents(string $sku): int {
    $invoice = $this->billing->totalCents($sku);
    return $invoice + intdiv($invoice, 4);
  }
}

The automated reproduction uses scripts/policy-tests.php, scripts/prepare.php and scripts/verify.php to validate the architecture policy, prepare five independent Composer roots, and verify their results. These supporting scripts belong to the tested fixture and are not reproduced in this article; the appendix provides a self-contained manual reproduction that does not require them.

In each case, Shipping is the only direct root package requirement, while Billing and Catalog are resolved through the actual package manifests. Every case exercises both services with the same synthetic inputs and checks the same functional result: 1200 cents for the invoice and 1500 cents including shipping.

I verified the complete matrix on Windows PowerShell 5.1 using PHP 8.4.24, Composer 2.10.2 and Deptrac 4.7.2. The root Composer manifest passed strict validation, and all five independent Composer installations completed successfully.

In the separate automated reproduction fixture, I executed the complete matrix with:

composer run matrix

Output (Composer installation details omitted):

Policy checks PASS
Prepared five independent Composer roots.
baseline: runtime PASS; architecture PASS
internal: runtime PASS; architecture FAIL as expected
transitive: runtime PASS; architecture FAIL as expected
combined: runtime PASS; architecture FAIL as expected
fixed: runtime PASS; architecture PASS
Matrix PASS

The observed results were:

  • Baseline - PHP runtime Pass, Architecture check Pass, Deptrac violations 0
  • Internal API reference - PHP runtime Pass, Architecture check Fail as expected: Billing → Catalog internal, Deptrac violations 1
  • Undeclared direct reference - PHP runtime Pass, Architecture check Fail as expected: Shipping → Catalog public, Deptrac violations 1
  • Both violations - PHP runtime Pass, Architecture check Fail as expected: both references, Deptrac violations 2
  • Both corrected - PHP runtime Pass, Architecture check Pass, Deptrac violations 0

All five scenarios completed their runtime checks successfully. The architecture gate accepted the baseline and corrected variants while rejecting the three variants containing the intended dependency violations.

The verified matrix provides stronger evidence than comparing two code snippets: all five scenarios satisfy identical functional assertions, while the architecture checks distinguish permitted dependencies from the intended violations.

A nonzero analysis exit code alone is not treated as evidence of a valid negative test. The automated verifier checks that the expected class relationships appear in the Deptrac report and rejects unexpected analysis errors, skipped violations and uncovered dependencies in this fixture. The successful matrix execution therefore confirms both the positive cases and the expected rejection behavior.

In the fixed case, Billing depends on the interface and Shipping declares the direct Catalog dependency. Neither fix requires changing the example's business output.

These results do not imply that functional tests are insufficient in general. They demonstrate that functional correctness and architectural compliance are separate properties: all five variants produce the expected business results, but only two satisfy the declared architecture policy. Architecture gates provide an additional form of verification by detecting source-level dependency violations that the functional checks in this experiment do not detect.

What this means for a modular framework

The experiment deliberately separates three decisions:

  1. Should a package be installed?
  2. Should a package be allowed to reference another package in its source?
  3. Which symbols of that package are part of its intended public API?

The answers can differ. An implementation might be necessary at runtime while consumers must depend only on a separate contracts package. A module might be installed without participating in the selected application composition. A package might be permitted as a dependency while some of its implementation classes remain internal.

These are policies a framework or application can define. They are not automatic guarantees provided by a namespace, Composer, or a directory structure.

Architecture analysis also has limits. Static analysis does not necessarily observe every runtime edge introduced through dynamic class names, reflection, service locators, configuration or generated code. A complete design should specify which of those mechanisms are permitted, who owns their validation, and how runtime composition is

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.