Architecture rules as dependency checks

Four classes, three layers, one deliberate mistake: an executed Deptrac exercise with 0/1/0 phases, exact diagnostics, and restored inputs.

Permitted connections and a visible boundary for an extra crossing.
Permitted connections and a visible boundary for an extra crossing.

The project rules say that the domain model does not depend on how it is displayed. During the next change, a convenient formatting call appears inside that model. The code remains syntactically valid, and the page even looks better. Yet changing the outer presentation may now require a change to the inner model. This is precisely the direction of dependency the rule was meant to prohibit.

Such a rule can become a check. It needs defined groups of classes, permitted relationships between them, and an analyser that reads the actual PHP code. A separate question is whether the check notices a deliberately introduced violation: it should accept the initial code, reject one intentional change, and accept the restored version again.

The small independent exercise ran in one Symfony 8.1 Demo on PHP 8.5.12 with Deptrac 4.7.2 installed. Three real phases produced analyse exit codes 0 → 1 → 0 and violation counts 0 → 1 → 0. Allowed remained 3, and original inputs were unchanged after the experiment. These are three static-analysis phases, not three PHPUnit tests.

Start with a rule that has a clear subject

The teaching task works with the text of a note. Note stores that text, NoteText reads it for an application use case, MemoryNotes creates a synthetic note, and TextDecoration can add presentation details. These four classes belong to one small capability, but they have different roles.

Layer Classes Permitted dependencies on other layers
Domain Note None
Application NoteText Domain
Infrastructure MemoryNotes, TextDecoration Domain

The matrix describes this example only. It does not require every project to have exactly three layers or these directory names. Its reason is specific: the note value should remain available without knowing about an external decorator. Code that creates or uses a note may know its type.

The arrow needs to be read correctly. The dependency MemoryNotes → Note means that the code of the first class refers to the second. It does not describe the direction of data flow in a running program. A factory can return the note it creates to its caller, while the static dependency still points from the factory to the type it uses.

Deptrac configuration defines permissions between layers through ruleset; the layer and violation model is described in the tool's official core concepts. This fragment is sufficient for our matrix:

ruleset:
  Domain: []
  Application: [Domain]
  Infrastructure: [Domain]

The matrix does not detail relationships between classes within the same layer. Nor does it decide whether the rule itself is useful: the person responsible for the architecture must explain its basis.

Derive the graph from PHP code

The exercise selects deptrac/deptrac version 4.7.2. Its Composer declaration specifies PHP ^8.2, support for Symfony components ^8.0, and a dependency on nikic/php-parser. The teaching application has its own Symfony 8.1.* and PHP >=8.4 profile. In this run, Composer installed the candidate in the same application, and check-platform-reqs passed.

Deptrac builds reference information by parsing PHP. In the selected version, the default Nikic parser creates syntax nodes and performs name resolution. The check can therefore work with a fully qualified class name, rather than merely a use line found somewhere in a file.

This exercise explicitly selects analyser.types: [class]. The configuration reference distinguishes analysis of classes, imports, functions, and other constructs. The selected mode defines the scope of the result: we check references that this mode extracts from classes, rather than every possible relationship between arbitrary parts of a PHP program.

The classLike collectors assign discovered classes by their full namespace. Domain uses the prefix App\DependencyRules\Domain\; the other layers use their own corresponding prefixes. Here, a regular expression only assigns an already discovered symbol to a layer. The PHP analyser reads the dependency graph. The exercise's Python script runs that analyser and checks its report; it does not infer dependencies by searching for text matches in source.

A green result starts with nonempty input

The scan path is limited to src/DependencyRules. It contains four specified PHP files, excluding the rest of the application, its tests, and the mutation fixture. This narrow scope makes the example understandable, but it must be checked: an incorrect path could leave the analyser with an empty directory.

Before each phase, the prepared runner checks the exact file set and bytes, runs PHP lint, and then reads symbol membership in the layers. The debug:layer command must show the expected classes in each group; debug:unassigned must leave no unassigned symbols. Both commands are described in the Deptrac debugging documentation.

The check also requires at least one allowed dependency in the report. This adds protection against empty or incorrectly configured analysis. Files merely existing on disk is insufficient: the tool must show that it actually included the intended symbols in its model.

The record separately captures the PHP and Composer versions, the installed and locked Deptrac version, the configuration, and the input files. Reading a release number does not establish that this tool is already installed. The exercise therefore checks both the lock and installed metadata before running.

One error, an unchanged criterion

The original Note::text() method returns the stored string. A different version of the same file is prepared for the negative control: one return statement starts calling the outer decorator.

return \App\DependencyRules\Infrastructure\TextDecoration::wrap($this->text);

The call uses a fully qualified class name and needs no new use statement. It creates a specific forbidden dependency: Domain now knows about Infrastructure. The change remains ordinary PHP code; a syntax error would not provide a suitable check of the architectural boundary.

All three phases use the same rules, collectors, and diagnostic criteria. The analyser cache is disabled with --no-cache so that a source change does not depend on a previously cached parse; this option is described in the run instructions.

Phase Input Expected result
baseline The initial four classes Exit 0, no violations
mutated One return statement in Note changed Exit 1, one exact forbidden dependency
reverted The original bytes restored Exit 0, no violations again

Here, baseline means the initial source version. No list of accepted old violations is added to the configuration. The error must therefore remain visible after the mutation.

Comparing bytes after restoration serves a practical purpose. It distinguishes restoration of the initial experiment from another fix that happens to pass the check too. Changing the rule or broadening exclusions together with the source could produce success without preserving the intended boundary.

A refusal must name the wrong relationship

A nonzero exit code is insufficient on its own. A missing package, broken configuration, or read error can produce one as well. The negative control needs a complete JSON report containing the specific architectural reason.

The Deptrac JSON formatter includes summary counts and messages grouped by file. The prepared criterion expects one message: App\DependencyRules\Domain\Note depends on App\DependencyRules\Infrastructure\TextDecoration, with the direction Domain on Infrastructure. It must point to the changed return statement in src/DependencyRules/Domain/Note.php.

There must also be no skipped violations, uncovered dependencies, analysis warnings, or analysis errors. Missing or incomplete JSON stops the check too. This makes the failing process useful evidence: it shows that the intended rule noticed the intended change.

That message identifies what needs fixing. In our case, presentation should remain in the outer part, while Note returns to storing text. Adding an exception to skip_violations changes policy. It requires its own reason and review, rather than automatic application after every inconvenient refusal.

One application and temporary analysis

The new files are added to the existing teaching Symfony application. There is no separate skeleton or second Composer root. The classes are static fixtures for this exercise: they need no new routes, container services, or changes to existing pages.

After reviewing dependency changes, the tool is installed in the development dependencies of that same application:

composer require --dev deptrac/deptrac:4.7.2

The runner uses the analyser installed there, but copies only the four selected source files and the rule into a temporary directory. Mutation and restoration happen in that copy. The Composer manifest, lock, Kernel, and vendor remain in one application; the exercise's working PHP files are not rewritten.

Running the prepared sequence requires PHP, Composer, an installed Deptrac, and Python with its standard library. From the application root, the command looks like this; the report path must be new and outside the application:

python tools/dependency-rules/run_gate.py \
  --demo . \
  --output /tmp/dependency-rules-run.json

The actual report retains commands, exit codes, class membership, JSON diagnostics, and binding to input bytes for each phase. Baseline and reverted have zero violations, while mutated has exactly one forbidden edge; skipped, uncovered, warnings, and errors are zero.

Where the rule's evidence ends

Successful analysis would mean that the selected source dependencies conform to the specified matrix. It would not establish whether the note displays correctly, container wiring works, or behavior meets a consumer's needs. Those questions require their own checks.

Dynamic class names, reflection, hidden runtime calls, and configuration relationships may need another method. Likewise, a directory containing four classes provides no conclusion about the whole application. Expanding the scan path changes the subject of the check and calls for another review of rules and coverage.

An architectural record explains why a boundary exists. The analyser helps identify a specific violation of that boundary in code. When both are tied to exact inputs and a clear refusal, the next change has a checkable reference: the dependency can be found, discussed, and corrected without reconstructing the intent from memory.

  1. Repository governance Rules that survive the next development session
  2. Symfony Core Where the controller ends: one use case for creating a note in Symfony
  3. Standards & Governance From candidate to standard: when a rule earns mandatory status

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article