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.

1. 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:

Mechanism Question it answers
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.

2. 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.

3. 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.

4. 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.

5. 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.

6. 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:

Case PHP runtime Architecture check Deptrac violations
Baseline Pass Pass 0
Internal API reference Pass Fail as expected: Billing → Catalog internal 1
Undeclared direct reference Pass Fail as expected: Shipping → Catalog public 1
Both violations Pass Fail as expected: both references 2
Both corrected Pass Pass 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.

7. 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 checked. An architecture gate is not a security sandbox: it is an executable policy over a defined set of source dependencies.

8. How Coretsia approaches package boundaries

These distinctions are important in the design of Coretsia, the PHP framework I am developing. Coretsia maintains a canonical direct compile-time dependency matrix for its layered framework packages. An allowed edge from A to B does not grant A permission to reference every package reachable through B.

The matrix is distinct from the installation graph. In the repository snapshot reviewed for this article, the HTTP platform package directly requires the Redaction package in Composer, and its module metadata requires platform.redaction. Its source permission, however, does not include platform/redaction. The HTTP provider consumes SensitiveDataRedactorInterface and SensitiveKeyClassifierInterface from core/contracts. The Redaction implementation is a runtime prerequisite; the interfaces are the source-level dependency.

That distinction is enforced in the repository's architecture tooling. The Deptrac generator validates internal Composer requirements against the source matrix and the separately permitted runtime-module installation relationships. It generates static source permissions from the canonical matrix, not from all installed packages.

The generated Deptrac configuration consequently allows HTTP to reference the designated core packages without adding a source edge to Redaction. The repository's integration tests include cases for keeping runtime-only Composer requirements out of the generated source rules, rejecting missing direct Composer requirements for runtime modules, and detecting forbidden or cyclic package edges.

Coretsia also has a separate Kernel public API evidence file and a gate that checks declared Kernel symbols against that evidence and recognized internal markers. This is a different check from the package-level Deptrac rules: it checks consistency of the Kernel's stated public surface, not every possible cross-package call into internal code.

The synthetic four-layer Deptrac example presented here is not copied from Coretsia's generated package rules. It illustrates the same separation of concerns on a smaller, independently reproducible problem.

9. Conclusion

Folders provide organization, package declarations describe installation requirements, and public contracts describe intended interaction. None of those mechanisms alone proves that source code respects the architecture. By describing allowed relationships independently, analysing actual references, and testing both permitted and forbidden cases, we can turn an architectural intention into an executable check.

That is the point of enforceable modularity: not merely to make code look modular, but to make violations observable before the code is merged.

Appendix: reproduce the experiment manually

The following is a self-contained manual reproduction of the five runtime and architecture outcomes, without the automated fixture scripts. It uses the same PHP classes, package dependency relationships and Deptrac rules, but simplifies some supporting details: the Composer manifests omit optional metadata, and run.php wires the services directly instead of using the automated fixture's separate wiring files and installation assertions. Use a distinct case directory for each variant so that Composer installations are independent.

Create a tooling directory and save this as its composer.json:

{ "name": "acme/boundary-tools", "require": {"php": "~8.4.0"}, "require-dev": {"deptrac/deptrac": "4.7.2"}, "config": {"allow-plugins": false} } 

Run composer update --no-interaction --no-plugins --no-scripts in that directory. In the following commands, assume the tooling directory is named tools and is a sibling of each case.

Create a case directory with the package tree from section 2. Use the complete PHP classes from sections 2–6. Each package has its own manifest under packages/.

packages/catalog/composer.json:

{ "name": "acme/catalog", "version": "1.0.0", "require": {"php": "~8.4.0"}, "autoload": {"psr-4": {"Acme\\Catalog\\": "src/"}} } 

packages/billing/composer.json:

{ "name": "acme/billing", "version": "1.0.0", "require": {"php": "~8.4.0", "acme/catalog": "1.0.0"}, "autoload": {"psr-4": {"Acme\\Billing\\": "src/"}} } 

packages/shipping/composer.json (use the require block from section 4 for the fixed case):

{ "name": "acme/shipping", "version": "1.0.0", "require": {"php": "~8.4.0", "acme/billing": "1.0.0"}, "autoload": {"psr-4": {"Acme\\Shipping\\": "src/"}} } 

Save this as composer.json in the case root, not in a package:

{ "name": "acme/experiment", "require": {"php": "~8.4.0", "acme/shipping": "1.0.0"}, "repositories": [ {"type": "path", "url": "packages/*", "options": {"symlink": false, "reference": "config"}}, {"packagist.org": false} ], "config": {"allow-plugins": false} } 

Create run.php at the case root:

<?php declare(strict_types=1); use Acme\Billing\InvoiceService; use Acme\Catalog\Internal\PriceCalculator; use Acme\Shipping\ShippingService; require __DIR__ . '/vendor/autoload.php'; $prices = new PriceCalculator(); $billing = new InvoiceService($prices); $shipping = new ShippingService($billing); // For transitive, combined and fixed cases replace the line above with: // $shipping = new ShippingService($billing, $prices); if ($billing->totalCents('demo') !== 1200 || $shipping->totalCents('demo') !== 1500) { throw new RuntimeException('Unexpected functional result.'); } echo "Runtime PASS: invoice=1200, shipping-inclusive total=1500\n"; 

Create deptrac.yaml:

deptrac: paths: - packages/billing/src - packages/catalog/src - packages/shipping/src layers: - name: billing_api collectors: - type: classLike value: '^Acme\\Billing\\.*' - name: catalog_api collectors: - type: classLike value: '^Acme\\Catalog\\Contracts\\.*' - name: catalog_internal collectors: - type: classLike value: '^Acme\\Catalog\\Internal\\.*' - name: shipping_api collectors: - type: classLike value: '^Acme\\Shipping\\.*' ruleset: billing_api: [catalog_api] catalog_api: [] catalog_internal: [catalog_api] shipping_api: [billing_api] 

For the fixed case only, add catalog_api to shipping_api's allowed targets. Never add catalog_internal. The automated experiment derives this ruleset rather than asking you to edit it by hand.

From a fresh case root:

composer update --no-interaction --no-plugins --no-scripts --no-audit php run.php php ../tools/vendor/bin/deptrac analyse --config-file=deptrac.yaml --no-cache 

To reproduce the five cases, choose the class versions and manifest entries in the verification matrix:

  • Baseline: contract-based Billing and baseline Shipping.
  • Internal: implementation-based Billing and baseline Shipping.
  • Transitive: contract-based Billing and direct-price Shipping, without the additional require entry.
  • Combined: implementation-based Billing and direct-price Shipping, without the additional require entry.
  • Fixed: contract-based Billing and direct-price Shipping, with the additional require entry and corresponding source permission.

References

Disclosure: AI was used to help draft this article and prepare the example.