Laravel Architecture Patterns
Agent Workflow (MANDATORY)
Before ANY implementation, spawn 3 agents in parallel, one Agent call each with a name:
- fuse-ai-pilot:explore-codebase - Analyze existing architecture
- fuse-ai-pilot:research-expert - Verify Laravel patterns via Context7
- mcp__context7__query-docs - Check service container and DI patterns
After implementation, run fuse-ai-pilot:sniper for validation.
Overview
Laravel architecture focuses on clean separation of concerns, dependency injection, and maintainable code organization. This skill covers everything from project structure to production deployment.
When to Use
- Structuring new Laravel projects
- Implementing services, repositories, actions
- Setting up dependency injection
- Configuring development environments
- Deploying to production
Critical Rules
- Thin controllers - Delegate business logic to services
- Interfaces in app/Contracts/ - Never alongside implementations
- DI over facades - Constructor injection for testability
- Files < 100 lines - Split larger files per SOLID
- Environment separation - .env never committed
Architecture
app/
├── Actions/ # Single-purpose action classes
├── Contracts/ # Interfaces (DI)
├── DTOs/ # Data transfer objects
├── Enums/ # PHP 8.1+ enums
├── Events/ # Domain events
├── Http/
│ ├── Controllers/ # Thin controllers
│ ├── Middleware/ # Request filters
│ ├── Requests/ # Form validation
│ └── Resources/ # API transformations
├── Jobs/ # Queued jobs
├── Listeners/ # Event handlers
├── Models/ # Eloquent models only
├── Policies/ # Authorization
├── Providers/ # Service registration
├── Repositories/ # Data access layer
└── Services/ # Business logic
Reference Guide
Core Architecture
| Reference |
When to Use |
| container.md |
Dependency injection, binding, resolution |
| providers.md |
Service registration, bootstrapping |
| facades.md |
Static proxies, real-time facades |
| contracts.md |
Interfaces, loose coupling |
| structure.md |
Directory organization |
| lifecycle.md |
Request handling flow |
Configuration & Setup
| Reference |
When to Use |
| configuration.md |
Environment, config files |
| installation.md |
New project setup |
| upgrade.md |
Version upgrades, breaking changes |
| releases.md |
Release notes, versioning |
Development Environments
| Reference |
When to Use |
| sail.md |
Docker development |
| valet.md |
macOS native development |
| homestead.md |
Vagrant (legacy) |
| octane.md |
High-performance servers |
Utilities & Tools
| Reference |
When to Use |
| artisan.md |
CLI commands, custom commands |
| helpers.md |
Global helper functions |
| filesystem.md |
File storage, S3, local |
| processes.md |
Shell command execution |
| context.md |
Request-scoped data sharing |
Advanced Features
| Reference |
When to Use |
| pennant.md |
Feature flags |
| mcp.md |
Model Context Protocol |
| concurrency.md |
Parallel execution |
Operations
| Reference |
When to Use |
| deployment.md |
Production deployment |
| envoy.md |
SSH task automation |
| logging.md |
Log channels, formatting |
| errors.md |
Exception handling |
| packages.md |
Creating packages |
Templates
| Template |
Purpose |
| UserService.php.md |
Service + repository pattern |
| AppServiceProvider.php.md |
DI bindings, bootstrapping |
| ArtisanCommand.php.md |
CLI commands, signatures, I/O |
| McpServer.php.md |
MCP servers, tools, resources, prompts |
| PennantFeature.php.md |
Feature flags, A/B testing |
| Envoy.blade.php.md |
SSH deployment automation |
| sail-config.md |
Docker Sail configuration |
| octane-config.md |
FrankenPHP, Swoole, RoadRunner |
Feature Matrix
| Feature |
Reference |
Priority |
| Service Container |
container.md |
High |
| Service Providers |
providers.md |
High |
| Directory Structure |
structure.md |
High |
| Configuration |
configuration.md |
High |
| Installation |
installation.md |
High |
| Octane (Performance) |
octane.md |
High |
| Sail (Docker) |
sail.md |
High |
| Artisan CLI |
artisan.md |
Medium |
| Deployment |
deployment.md |
Medium |
| Envoy (SSH) |
envoy.md |
Medium |
| Facades |
facades.md |
Medium |
| Contracts |
contracts.md |
Medium |
| Valet (macOS) |
valet.md |
Medium |
| Upgrade Guide |
upgrade.md |
Medium |
| Logging |
logging.md |
Medium |
| Errors |
errors.md |
Medium |
| Lifecycle |
lifecycle.md |
Medium |
| Filesystem |
filesystem.md |
Medium |
| Helpers |
helpers.md |
Low |
| Pennant (Flags) |
pennant.md |
Low |
| Context |
context.md |
Low |
| Processes |
processes.md |
Low |
| Concurrency |
concurrency.md |
Low |
| MCP |
mcp.md |
Low |
| Packages |
packages.md |
Low |
| Releases |
releases.md |
Low |
| Homestead |
homestead.md |
Low |
Quick Reference
Service Injection
public function __construct(
private readonly UserServiceInterface $userService,
) {}
Service Provider Binding
public function register(): void
{
$this->app->bind(UserServiceInterface::class, UserService::class);
$this->app->singleton(CacheService::class);
}
Artisan Command
php artisan make:provider CustomServiceProvider
php artisan make:command ProcessOrders
Environment Access
$debug = env('APP_DEBUG', false);
$config = config('app.name');
Laravel 13 Notes
Stack mis à jour
- Symfony 7.4 et 8.0 supportés en parallèle (HttpFoundation, Console, Mailer)
- PHP 8.3 minimum (8.2 retiré)
- pda/pheanstalk 8.0+ requis si driver Beanstalk
Cache::touch() API
Nouvelle méthode pour rafraîchir le TTL sans recalculer la valeur.
Cache::touch('user:123', now()->addHour());
Cache::touch(['user:123', 'user:456'], 3600);
Queue::route() pour routing dynamique
Voir [[laravel-queues]] pour le routing déclaratif par job (connexion/queue cible via configuration plutôt que sur chaque job).
new Model() dans boot() → LogicException
Laravel 13 jette une LogicException si vous instanciez un modèle Eloquent dans register() d'un ServiceProvider (container pas prêt). Utiliser boot() ou un listener.
Migration Laravel 12 → 13
| Sujet |
Avant (12) |
Après (13) |
| PHP minimum |
8.2 |
8.3 |
| PHPUnit |
11 |
12 |
| Pest |
3 |
4 |
| CSRF |
VerifyCsrfToken |
PreventRequestForgery (origin-aware) |
| Cache prefix |
underscore |
hyphens par défaut (configurer CACHE_PREFIX, REDIS_PREFIX, SESSION_COOKIE pour rétro-compat) |
| Beanstalk |
pheanstalk 7.x |
pheanstalk 8.0+ |
| Symfony |
7.x |
7.4 / 8.0 |
| Model boot |
toléré |
new Model() → LogicException |
| Config |
— |
nouveau serializable_classes (allowlist hardening) |
# Rétro-compat cache prefixes pour upgrade depuis L12
CACHE_PREFIX=laravel_cache_
REDIS_PREFIX=laravel_database_
SESSION_COOKIE=laravel_session
// config/app.php — durcissement deserialize
'serializable_classes' => [
App\DTO\PaymentDto::class,
App\DTO\OrderDto::class,
],
Best Practices
DO
- Utiliser
final readonly class pour DTOs et Value Objects (PHP 8.3+)
- Injecter via constructor promotion +
interface (DI inversion)
- Logger via
Context::add() pour propager metadata entre jobs/requêtes
- Configurer
serializable_classes en production
- Préférer
app(Contract::class) sur App::make() (typage strict)
DON'T
- Instancier des modèles dans
register() (→ LogicException L13)
- Hardcoder des chemins absolus (utiliser
base_path(), storage_path())
- Mélanger Repository et Service (un par responsabilité)
- Bypasser le container avec
new ConcreteClass()
- Ignorer le bump du préfixe cache lors d'un upgrade depuis L12
1---2name: laravel-architecture3description: Use when structuring a Laravel project, creating services/repositories/actions, implementing dependency injection, or organizing code layers.4---56<objective>7Covers Laravel application architecture end to end: project structure8(Actions, Contracts, DTOs, Services, Repositories layout), the service9container and dependency injection, service providers and facades,10environment/configuration, development environments (Sail, Valet, Homestead,11Octane), Artisan CLI, filesystem/processes/context, feature flags (Pennant),12MCP servers, concurrency, and production deployment (including Envoy,13logging, error handling, and package authoring).14</objective>1516# Laravel Architecture Patterns1718## Agent Workflow (MANDATORY)1920Before ANY implementation, spawn 3 agents in parallel, one `Agent` call each with a `name`:21221. **fuse-ai-pilot:explore-codebase** - Analyze existing architecture232. **fuse-ai-pilot:research-expert** - Verify Laravel patterns via Context7243. **mcp__context7__query-docs** - Check service container and DI patterns2526After implementation, run **fuse-ai-pilot:sniper** for validation.2728---2930## Overview3132Laravel architecture focuses on clean separation of concerns, dependency injection, and maintainable code organization. This skill covers everything from project structure to production deployment.3334### When to Use3536- Structuring new Laravel projects37- Implementing services, repositories, actions38- Setting up dependency injection39- Configuring development environments40- Deploying to production4142---4344## Critical Rules45461. **Thin controllers** - Delegate business logic to services472. **Interfaces in app/Contracts/** - Never alongside implementations483. **DI over facades** - Constructor injection for testability494. **Files < 100 lines** - Split larger files per SOLID505. **Environment separation** - .env never committed5152---5354## Architecture5556```text57app/58├── Actions/ # Single-purpose action classes59├── Contracts/ # Interfaces (DI)60├── DTOs/ # Data transfer objects61├── Enums/ # PHP 8.1+ enums62├── Events/ # Domain events63├── Http/64│ ├── Controllers/ # Thin controllers65│ ├── Middleware/ # Request filters66│ ├── Requests/ # Form validation67│ └── Resources/ # API transformations68├── Jobs/ # Queued jobs69├── Listeners/ # Event handlers70├── Models/ # Eloquent models only71├── Policies/ # Authorization72├── Providers/ # Service registration73├── Repositories/ # Data access layer74└── Services/ # Business logic75```7677---7879## Reference Guide8081### Core Architecture8283| Reference | When to Use |84|-----------|-------------|85| [container.md](references/container.md) | Dependency injection, binding, resolution |86| [providers.md](references/providers.md) | Service registration, bootstrapping |87| [facades.md](references/facades.md) | Static proxies, real-time facades |88| [contracts.md](references/contracts.md) | Interfaces, loose coupling |89| [structure.md](references/structure.md) | Directory organization |90| [lifecycle.md](references/lifecycle.md) | Request handling flow |9192### Configuration & Setup9394| Reference | When to Use |95|-----------|-------------|96| [configuration.md](references/configuration.md) | Environment, config files |97| [installation.md](references/installation.md) | New project setup |98| [upgrade.md](references/upgrade.md) | Version upgrades, breaking changes |99| [releases.md](references/releases.md) | Release notes, versioning |100101### Development Environments102103| Reference | When to Use |104|-----------|-------------|105| [sail.md](references/sail.md) | Docker development |106| [valet.md](references/valet.md) | macOS native development |107| [homestead.md](references/homestead.md) | Vagrant (legacy) |108| [octane.md](references/octane.md) | High-performance servers |109110### Utilities & Tools111112| Reference | When to Use |113|-----------|-------------|114| [artisan.md](references/artisan.md) | CLI commands, custom commands |115| [helpers.md](references/helpers.md) | Global helper functions |116| [filesystem.md](references/filesystem.md) | File storage, S3, local |117| [processes.md](references/processes.md) | Shell command execution |118| [context.md](references/context.md) | Request-scoped data sharing |119120### Advanced Features121122| Reference | When to Use |123|-----------|-------------|124| [pennant.md](references/pennant.md) | Feature flags |125| [mcp.md](references/mcp.md) | Model Context Protocol |126| [concurrency.md](references/concurrency.md) | Parallel execution |127128### Operations129130| Reference | When to Use |131|-----------|-------------|132| [deployment.md](references/deployment.md) | Production deployment |133| [envoy.md](references/envoy.md) | SSH task automation |134| [logging.md](references/logging.md) | Log channels, formatting |135| [errors.md](references/errors.md) | Exception handling |136| [packages.md](references/packages.md) | Creating packages |137138---139140## Templates141142| Template | Purpose |143|----------|---------|144| [UserService.php.md](references/templates/UserService.php.md) | Service + repository pattern |145| [AppServiceProvider.php.md](references/templates/AppServiceProvider.php.md) | DI bindings, bootstrapping |146| [ArtisanCommand.php.md](references/templates/ArtisanCommand.php.md) | CLI commands, signatures, I/O |147| [McpServer.php.md](references/templates/McpServer.php.md) | MCP servers, tools, resources, prompts |148| [PennantFeature.php.md](references/templates/PennantFeature.php.md) | Feature flags, A/B testing |149| [Envoy.blade.php.md](references/templates/Envoy.blade.php.md) | SSH deployment automation |150| [sail-config.md](references/templates/sail-config.md) | Docker Sail configuration |151| [octane-config.md](references/templates/octane-config.md) | FrankenPHP, Swoole, RoadRunner |152153---154155## Feature Matrix156157| Feature | Reference | Priority |158|---------|-----------|----------|159| Service Container | container.md | High |160| Service Providers | providers.md | High |161| Directory Structure | structure.md | High |162| Configuration | configuration.md | High |163| Installation | installation.md | High |164| Octane (Performance) | octane.md | High |165| Sail (Docker) | sail.md | High |166| Artisan CLI | artisan.md | Medium |167| Deployment | deployment.md | Medium |168| Envoy (SSH) | envoy.md | Medium |169| Facades | facades.md | Medium |170| Contracts | contracts.md | Medium |171| Valet (macOS) | valet.md | Medium |172| Upgrade Guide | upgrade.md | Medium |173| Logging | logging.md | Medium |174| Errors | errors.md | Medium |175| Lifecycle | lifecycle.md | Medium |176| Filesystem | filesystem.md | Medium |177| Helpers | helpers.md | Low |178| Pennant (Flags) | pennant.md | Low |179| Context | context.md | Low |180| Processes | processes.md | Low |181| Concurrency | concurrency.md | Low |182| MCP | mcp.md | Low |183| Packages | packages.md | Low |184| Releases | releases.md | Low |185| Homestead | homestead.md | Low |186187---188189## Quick Reference190191### Service Injection192193```php194public function __construct(195 private readonly UserServiceInterface $userService,196) {}197```198199### Service Provider Binding200201```php202public function register(): void203{204 $this->app->bind(UserServiceInterface::class, UserService::class);205 $this->app->singleton(CacheService::class);206}207```208209### Artisan Command210211```shell212php artisan make:provider CustomServiceProvider213php artisan make:command ProcessOrders214```215216### Environment Access217218```php219$debug = env('APP_DEBUG', false);220$config = config('app.name');221```222223---224225## Laravel 13 Notes226227### Stack mis à jour228- **Symfony 7.4 et 8.0** supportés en parallèle (HttpFoundation, Console, Mailer)229- **PHP 8.3 minimum** (8.2 retiré)230- **pda/pheanstalk 8.0+** requis si driver Beanstalk231232### Cache::touch() API233Nouvelle méthode pour rafraîchir le TTL sans recalculer la valeur.234235```php236Cache::touch('user:123', now()->addHour());237Cache::touch(['user:123', 'user:456'], 3600);238```239240### Queue::route() pour routing dynamique241Voir [[laravel-queues]] pour le routing déclaratif par job (connexion/queue cible via configuration plutôt que sur chaque job).242243### `new Model()` dans boot() → LogicException244Laravel 13 jette une `LogicException` si vous instanciez un modèle Eloquent dans `register()` d'un ServiceProvider (container pas prêt). Utiliser `boot()` ou un listener.245246## Migration Laravel 12 → 13247248| Sujet | Avant (12) | Après (13) |249|-------|-----------|------------|250| PHP minimum | 8.2 | **8.3** |251| PHPUnit | 11 | **12** |252| Pest | 3 | **4** |253| CSRF | `VerifyCsrfToken` | **`PreventRequestForgery`** (origin-aware) |254| Cache prefix | underscore | **hyphens par défaut** (configurer `CACHE_PREFIX`, `REDIS_PREFIX`, `SESSION_COOKIE` pour rétro-compat) |255| Beanstalk | pheanstalk 7.x | **pheanstalk 8.0+** |256| Symfony | 7.x | **7.4 / 8.0** |257| Model boot | toléré | **`new Model()` → LogicException** |258| Config | — | nouveau `serializable_classes` (allowlist hardening) |259260```env261# Rétro-compat cache prefixes pour upgrade depuis L12262CACHE_PREFIX=laravel_cache_263REDIS_PREFIX=laravel_database_264SESSION_COOKIE=laravel_session265```266267```php268// config/app.php — durcissement deserialize269'serializable_classes' => [270 App\DTO\PaymentDto::class,271 App\DTO\OrderDto::class,272],273```274275## Best Practices276277### DO278- Utiliser `final readonly class` pour DTOs et Value Objects (PHP 8.3+)279- Injecter via constructor promotion + `interface` (DI inversion)280- Logger via `Context::add()` pour propager metadata entre jobs/requêtes281- Configurer `serializable_classes` en production282- Préférer `app(Contract::class)` sur `App::make()` (typage strict)283284### DON'T285- Instancier des modèles dans `register()` (→ LogicException L13)286- Hardcoder des chemins absolus (utiliser `base_path()`, `storage_path()`)287- Mélanger Repository et Service (un par responsabilité)288- Bypasser le container avec `new ConcreteClass()`289- Ignorer le bump du préfixe cache lors d'un upgrade depuis L12