Enforce software layer dependencies with deptrac

Deptrac is a tool recently announced by Sensionlabs. It helps you keep dependencies between the different layers in your architecture under better control by providing insight into the current state of the dependencies and warns you when unwanted dependencies get introduced. To use Deptrac in your application either download the .phar file or add the following dependencies to your Composer configuration:





composer.phar require sensiolabs-de/deptrac composer.phar require loostro/deptrac-shim



I prefer to install Deptrac via Composer locally as I do not like the globally install Composer packages or other tools (except for Composer - but that is a different story). To set up Deptrac for your application run the following command which will create a default configuration called depfile.yml in the root directory of your application.





./vendor/bin/deptrac init



Given we use a micro framework like Adrenaline we want a clear separation between the Http layer and the Application layer. We do not want to directly depend on Request or Response objects in our Application layer. But the Http layer - our action classes specifically - should be able to make use of the classes from the Application layer. In the Deptrac configuration we can configure each of our layers and define so called collectors to identify the classes for each layer. Out-of-the-box you are able to define regular expressions to match class names. In case this is not sufficient simply create your own collector class. A layer configuration could look like this:





layers: - name: Http collectors: - type: className regex: .*Http.* - name: App collectors: - type: className regex: .*App.*



As you can see we have defined 2 layers, one layer is called Http and captures all classes with "Http" in their class name. The other layer is called App and captures all class with "App" in their class name. In addition to that we need to refine the rulesets for Deptrac to work with:





ruleset: Http: - App App:



The notation is pretty simple: The Http layer is allowed to depend on the App layer. The App layer itself does not have any dependencies.





Let's run Deptrac to see what happens:





./vendor/bin/deptrac analyze depfile.yml



The output of Deptrac is as follows:





deptrac is alpha, not production ready. please help us and report feedback / bugs. Start to create an AstMap for 8 Files. ........ AstMap created. start emitting dependencies "InheritanceDependencyEmitter" start emitting dependencies "BasicDependencyEmitter" end emitting dependencies start flatten dependencies end flatten dependencies collecting violations. formatting dependencies. Found 0 Violations

No violations found. Perfect. Next up: Add Deptrac to your CI build pipeline.