Senior
What is clean architecture?
sobes.tech AI
Answer from AI
Clean Architecture is a set of software design principles proposed by Robert Martin (Uncle Bob), aimed at creating maintainable, testable, and flexible systems. The main idea is to divide the system into layers, where each layer depends only on the inner layers.
Main principles:
- Independence from frameworks: The system should not depend on any specific framework. Frameworks should be considered as tools, not the foundation of the architecture.
- Independence from tests: Business logic can be tested without a user interface, database, or external agents.
- Independence from user interface: The user interface can be easily changed without affecting the rest of the system.
- Independence from database: You can replace an SQL database with NoSQL or a file system without changing business logic.
- Independence from external agents: Business logic should not depend on external systems or services.
The architecture is usually divided into concentric circles:
- Entities: The innermost layer containing business rules that do not depend on the application. These are pure data objects and their logic.
- Use Cases (Interactors): Contains application business rules. Defines how entities interact. They depend only on entities.
- Interface Adapters: Transform data from formats suitable for Use Cases and Entities into formats suitable for the outer layers (e.g., for databases or web frameworks).
- Frameworks & Drivers: The outermost layer containing databases, web frameworks, UI, and other external dependencies.
Dependency rule: dependencies can only move inward. No outer circle should depend on an inner one.
Advantages:
- Improved testability.
- Flexibility and scalability.
- Independence from technologies.
- Simplified understanding of business logic.
Example directory structure in a PHP project:
// Root directory of the project
src/
Domain/ // Entities
Entity/
Service/ // Business services not tied to specific Use Cases
Application/ // Use Cases
UseCase/
Command/
Query/
// DTO (Data Transfer Objects - for passing data between layers)
DTO/
Infrastructure/ // Interface Adapters + Frameworks & Drivers
Persistence/ // Repositories, database adapters
Http/ // Controllers, Middleware
Cli/ // Console commands
// Framework-specific adapters (e.g., for Symfony or Laravel)
Framework/
// External services (API clients)
External/
Presentation/ // UI (e.g., Twig/Blade templates if UI is part of the project)
Templates/
config/ // Configuration files
public/ // Entry point (index.php)
tests/
Unit/
Integration/
Functional/
vendor/ // Composer dependencies