PHPackages                             giacomomasseron/php-clean-architecture - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. giacomomasseron/php-clean-architecture

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

giacomomasseron/php-clean-architecture
======================================

PHP version of the Clean Architecture by Robert C. Martin (Uncle Bob)

v2.0.0(1w ago)15404↓86.7%1MITPHPPHP ^8.2CI passing

Since Oct 10Pushed 1w agoCompare

[ Source](https://github.com/giacomomasseron/php-clean-architecture)[ Packagist](https://packagist.org/packages/giacomomasseron/php-clean-architecture)[ Docs](https://github.com/giacomomasseron/php-clean-architecture)[ GitHub Sponsors]()[ RSS](/packages/giacomomasseron-php-clean-architecture/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (39)Versions (16)Used By (0)

Implements Clean Architecture with PHP
======================================

[](#implements-clean-architecture-with-php)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6070ac29c46573572ef84910e6768755c86216db3e5c940792df02fcafea1e07/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f676961636f6d6f6d61737365726f6e2f7068702d636c65616e2d6172636869746563747572652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/giacomomasseron/php-clean-architecture)[![GitHub Tests Action Status](https://camo.githubusercontent.com/399bbabbbb2ec97a5215e72b366aa9aa62a203243f66bb3ce636e5524fc43937/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f676961636f6d6f6d61737365726f6e2f7068702d636c65616e2d6172636869746563747572652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/giacomomasseron/php-clean-architecture/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/33e3edd0d87641ff0472065c9ce0e771ce05bfa8c2120efff560320bfd26079e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f676961636f6d6f6d61737365726f6e2f7068702d636c65616e2d6172636869746563747572652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/giacomomasseron/php-clean-architecture/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/9232201ed66f5dda1d6a040e62d8bf26008d9024ba6202e3597f8386dc0bb525/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f676961636f6d6f6d61737365726f6e2f7068702d636c65616e2d6172636869746563747572652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/giacomomasseron/php-clean-architecture)

Implements Clean Architecture as described by Robert C. Martin (Uncle Bob) here:
[Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)

This is an opinionated package that defines levels of the architecture and the dependencies between them.
And uses deptrac to check if the levels are respected.

- [Installation](#installation)
- [Getting started](#Getting-started)
    - [Commands](#Commands)
        - [Install](#Install)
        - [Check](#Check)
        - [Rector](#Rector)
        - [Make Entity](#Make-Entity)
        - [Make Repository](#Make-Repository)
        - [Make UseCase](#Make-UseCase)
        - [Make Controller](#Make-Controller)
        - [Make Service](#Make-Service)
- [Why Clean Architecture](#Why-Clean-Architecture)
- [Concepts](#Concepts)
    - [Architecture Level](#Architecture-Level)
    - [UseCase](#UseCase)
- [How it works](#How-it-works)
    - [Levels](#Levels)
    - [Define a level inside the project](#Define-a-level-inside-the-project)
    - [UseCases](#UseCases)
        - [BaseUseCase](#BaseUseCase)
        - [Events](#events)
- [CI/CD](#CICD)
- [Testing](#testing)
- [Frameworks](#frameworks)
    - [Laravel](#laravel)
        - [Pulse](#pulse)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require giacomomasseron/php-clean-architecture
```

After the installation, you must run the *install* command to publish the *deptrac.yaml*, *php-clean-architecture.yaml* and *rector.php* config files to your root folder:

```
vendor/bin/php-clean-architecture install
```

Getting started
---------------

[](#getting-started)

To check the architecture levels in your project, use the following command:

```
vendor/bin/php-clean-architecture check
```

### Commands

[](#commands)

All make commands read the *php-clean-architecture.yaml* config file to know where to put the files created and which namespace they belong to.

#### Install

[](#install)

The install command publishes needed files your root folder.
If you have already rector installed, you must add these lines of code in your *rector.php* file:

```
return RectorConfig::configure() // This line is already present in your rector.php file
    ->withConfiguredRule(
        \GiacomoMasseroni\PHPCleanArchitecture\Rector\Rules\AddPHPCleanArchitectureInterfaceControllerToClassesRector::class,
        [
            'targetNamespaces' => [
                'App\Http\Controllers',
            ]
        ]
    )
    ->withConfiguredRule(
        \GiacomoMasseroni\PHPCleanArchitecture\Rector\Rules\AddPHPCleanArchitectureInterfaceEntityToClassesRector::class,
        [
            'targetNamespaces' => [
                'App\Entities',
            ]
        ]
    )
    ->withConfiguredRule(
        \GiacomoMasseroni\PHPCleanArchitecture\Rector\Rules\AddPHPCleanArchitectureInterfaceRepositoryToClassesRector::class,
        [
            'targetNamespaces' => [
                'App\Repositories',
            ]
        ]
    )
    ->withConfiguredRule(
        \GiacomoMasseroni\PHPCleanArchitecture\Rector\Rules\AddPHPCleanArchitectureInterfaceServiceToClassesRector::class,
        [
            'targetNamespaces' => [
                'App\Services',
            ]
        ]
    )
    ->withConfiguredRule(
        \GiacomoMasseroni\PHPCleanArchitecture\Rector\Rules\AddPHPCleanArchitectureInterfaceUseCaseToClassesRector::class,
        [
            'targetNamespaces' => [
                'App\UseCases',
            ]
        ]
    )
```

#### Check

[](#check)

The check command checks the architecture levels in your project.
You can use it in your CI/CD pipeline to be sure that the architecture levels are respected.

#### Rector

[](#rector)

The *rector* command adds the needed interfaces to your classes based on namespaces defined in your config files.

#### Make Entity

[](#make-entity)

To create an Entity, you can use the following command:

```
vendor/bin/php-clean-architecture make:entity EntityInYourProject
```

#### Make Repository

[](#make-repository)

To create a Repository, you can use the following command:

```
vendor/bin/php-clean-architecture make:repository UserRepository
```

#### Make UseCase

[](#make-usecase)

To create a UseCase, you can use the following command:

```
vendor/bin/php-clean-architecture make:usecase DoSomethingUseCase
```

#### Make Controller

[](#make-controller)

To create a Controller, you can use the following command:

```
vendor/bin/php-clean-architecture make:controller UserController
```

#### Make Service

[](#make-service)

To create a Service, you can use the following command:

```
vendor/bin/php-clean-architecture make:service ThirdyPartyService
vendor/bin/php-clean-architecture make:service ThirdyParty
```

In both cases, the created class will be named *ThirdyPartyService*.

Why Clean Architecture?
-----------------------

[](#why-clean-architecture)

Why not?
It is a well-known, well-structured architecture system.

Concepts
--------

[](#concepts)

### Architecture Level

[](#architecture-level)

In the Clean Architecture, a level is a layer of the architecture with a specific function, **only connected to the upper level**.

The rule of thumb of the Clean Architecture is:
**An inner circle must never know anything about the circles around it**.

### UseCase

[](#usecase)

UseCase is a concept of Use Cases level.

A UseCase is every action your project performs.
Good examples of use cases are:

- Login
- Register
- CompleteOrder
- UpdateProfile

**A use case should be a single, very specific action. It shouldn’t do anything more than its name suggests.**

How it works
------------

[](#how-it-works)

The package uses [deptrac](https://github.com/deptrac/deptrac) to define the levels and to check the dependencies between them.

### Levels

[](#levels)

These are the levels defined:

- Entity
- Repository
- UseCase
- Controller
- Service

These are the dependencies between the levels:

 ```
graph TD;
 Controller-->UseCase-->Repository; UseCase-->Service; Repository-->Service; Repository-->Entity;
```

      Loading The *Entity* level must not depend on any other level.
The *Repository* level can only depend on *Entity* or *Service* levels.
The *UseCase* level can only depend on *Repository* or *Service* levels.
The *Controller* level can only depend on *UseCase* levels.

**What is the Service level?**
The Service level can be used for third-party tools or libraries.

### Define a level inside the project

[](#define-a-level-inside-the-project)

The package comes with these interfaces:

- **EntityInterface**: implement this interface if the class belongs to the Entity level.
- **RepositoryInterface**: implement this interface if the class belongs to the Repository level.
- **UseCaseInterface**: implement this interface if the class belongs to the UseCase level.
- **ControllerInterface**: implement this interface if the class belongs to the Controller level.
- **ServiceInterface**: implement this interface if the class belongs to the Service level.

If you want your controller to be part of the Controller level, you need to implement the ControllerInterface.
For example:

```
use GiacomoMasseroni\PHPCleanArchitecture\Contracts\ControllerInterface;

public class YourController implements ControllerInterface
```

### UseCases

[](#usecases)

When you create a UseCase, the class needs to extend the BaseUseCase class, and you need to implement the UseCaseInterface.
For example:

```
use GiacomoMasseroni\PHPCleanArchitecture\BaseUseCase;
use GiacomoMasseroni\PHPCleanArchitecture\Contracts\UseCaseInterface;

public class DoSomething extends BaseUseCase implements UseCaseInterface
{
    public function handle(...$arguments): mixed
    {
        //
    }
}
```

To execute the UseCase, you need to call the *run* method defined in the BaseUseCase class:

```
DoSomething::run($arg1, $arg2);
```

#### BaseUseCase

[](#baseusecase)

The package defines an abstract class for use cases: *BaseUseCase*.
This class defines variable for the user executing the use case:

```
UseCaseExecutorInterface $executor
```

You can set the executor using the following example:

```
DoSomething::actingAs($user)->run($arg1, $arg2);
```

If you need to rollback the use case, you can override the *rollback* method:

```
public function rollback(): void
{
}
```

#### Events

[](#events)

The package dispatches two events, one when the use case starts, and one when the use case ends.
It uses the [Symfony Event Dispatcher Component](https://symfony.com/doc/current/components/event_dispatcher.html).

The events are:

- UseCaseStartedEvent
- UseCaseCompletedEvent

CI/CD
-----

[](#cicd)

If you want to check the architecture levels in your CI/CD pipeline, you can use the following command:

```
vendor/bin/php-clean-architecture check
```

This command will stop your pipeline if there are architecture violations, based on the deptrac configuration file.

Testing
-------

[](#testing)

```
composer test
```

Frameworks
----------

[](#frameworks)

### Laravel

[](#laravel)

[I wrote an article on how to use this package with Laravel](https://dev.to/giacomomasseron/clean-architecture-in-a-laravel-project-3oh3)

#### Pulse

[](#pulse)

Laravel pulse is a package that helps you to monitor the health of your Laravel application.
If you want to monitor use cases execution time, you can:

- Create two laravel events, `UseCaseStarted` and `UseCaseCompleted`
- Create a Pulse card that listens to these events and measures the execution time.
- Add this code to `register` function in `AppServiceProvider.php` file: ```
    \GiacomoMasseroni\PHPCleanArchitecture\Dispatcher::getInstance()->addListener(\GiacomoMasseroni\PHPCleanArchitecture\Events\UseCaseStartedEvent::class, function (\GiacomoMasseroni\PHPCleanArchitecture\Events\UseCaseStartedEvent $event): void {
        // Just propagate the event to Laravel event system
        \App\Events\UseCaseStarted::dispatch($event->useCase);
    });

    \GiacomoMasseroni\PHPCleanArchitecture\Dispatcher::getInstance()->addListener(\GiacomoMasseroni\PHPCleanArchitecture\Events\UseCaseCompletedEvent::class, function (\GiacomoMasseroni\PHPCleanArchitecture\Events\UseCaseCompletedEvent $event): void {
        // Just propagate the event to Laravel event system
        \App\Events\UseCaseCompleted::dispatch($event->useCase);
    });
    ```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Giacomo Masseroni](https://github.com/giacomomasseron)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance98

Actively maintained with recent releases

Popularity24

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 80.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~23 days

Recently: every ~57 days

Total

12

Last Release

7d ago

Major Versions

v0.3.0 → v1.0.02025-11-11

v1.0.2 → v2.0.02026-06-26

### Community

Maintainers

![](https://www.gravatar.com/avatar/504902576948b6d89fe41cd186b483afa89cc9de1b238005a5b7dcc51d33997e?d=identicon)[giacomomasseron](/maintainers/giacomomasseron)

---

Top Contributors

[![giacomomasseron](https://avatars.githubusercontent.com/u/16156317?v=4)](https://github.com/giacomomasseron "giacomomasseron (61 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (13 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (2 commits)")

---

Tags

clean-architectureclean-codephpclean architectureGiacomo Masseroni

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/giacomomasseron-php-clean-architecture/health.svg)

```
[![Health](https://phpackages.com/badges/giacomomasseron-php-clean-architecture/health.svg)](https://phpackages.com/packages/giacomomasseron-php-clean-architecture)
```

###  Alternatives

[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[drupal/core

Drupal is an open source content management platform powering millions of websites and applications.

21866.0M1.7k](/packages/drupal-core)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6942.5M421](/packages/drupal-core-recommended)[blackfire/player

A powerful web crawler and web scraper with Blackfire support

49617.1k](/packages/blackfire-player)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M574](/packages/shopware-core)[friendsoftypo3/content-blocks

TYPO3 CMS Content Blocks - Content Types API | Define reusable components via YAML

103519.9k53](/packages/friendsoftypo3-content-blocks)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
