laravel-architecture

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Laravel Architecture Patterns

Laravel 架构模式

Agent Workflow (MANDATORY)

Agent 工作流(强制要求)

Before ANY implementation, use
TeamCreate
to spawn 3 agents:
  1. fuse-ai-pilot:explore-codebase - Analyze existing architecture
  2. fuse-ai-pilot:research-expert - Verify Laravel patterns via Context7
  3. mcp__context7__query-docs - Check service container and DI patterns
After implementation, run fuse-ai-pilot:sniper for validation.

在开始任何实现工作前,使用
TeamCreate
生成3个Agent:
  1. fuse-ai-pilot:explore-codebase - 分析现有架构
  2. fuse-ai-pilot:research-expert - 通过Context7验证Laravel模式
  3. mcp__context7__query-docs - 检查服务容器和DI模式
实现完成后,运行fuse-ai-pilot:sniper进行验证。

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.
Laravel架构专注于关注点清晰分离、依赖注入和可维护的代码组织。本技能涵盖从项目结构到生产部署的所有内容。

When to Use

适用场景

  • Structuring new Laravel projects
  • Implementing services, repositories, actions
  • Setting up dependency injection
  • Configuring development environments
  • Deploying to production

  • 构建新的Laravel项目
  • 实现服务、仓库、动作
  • 配置依赖注入
  • 配置开发环境
  • 部署到生产环境

Critical Rules

核心规则

  1. Thin controllers - Delegate business logic to services
  2. Interfaces in app/Contracts/ - Never alongside implementations
  3. DI over facades - Constructor injection for testability
  4. Files < 100 lines - Split larger files per SOLID
  5. Environment separation - .env never committed

  1. 轻量控制器 - 将业务逻辑委托给服务
  2. 接口存放于app/Contracts/ - 绝不要与实现代码放在一起
  3. 优先使用DI而非Facades - 使用构造函数注入以提升可测试性
  4. 文件行数<100行 - 按照SOLID原则拆分较大文件
  5. 环境分离 - .env文件绝不提交到版本控制

Architecture

架构目录结构

text
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

text
app/
├── Actions/              # 单一职责的动作类
├── Contracts/            # 接口(用于DI)
├── DTOs/                 # 数据传输对象
├── Enums/                # PHP 8.1+ 枚举
├── Events/               # 领域事件
├── Http/
│   ├── Controllers/      # 轻量控制器
│   ├── Middleware/       # 请求过滤器
│   ├── Requests/         # 表单验证
│   └── Resources/        # API 数据转换
├── Jobs/                 # 队列任务
├── Listeners/            # 事件处理器
├── Models/               # 仅包含Eloquent模型
├── Policies/             # 授权策略
├── Providers/            # 服务注册
├── Repositories/         # 数据访问层
└── Services/             # 业务逻辑层

Reference Guide

参考指南

Core Architecture

核心架构

ReferenceWhen to Use
container.mdDependency injection, binding, resolution
providers.mdService registration, bootstrapping
facades.mdStatic proxies, real-time facades
contracts.mdInterfaces, loose coupling
structure.mdDirectory organization
lifecycle.mdRequest handling flow
参考文档适用场景
container.md依赖注入、绑定、解析
providers.md服务注册、初始化
facades.md静态代理、实时Facades
contracts.md接口、松耦合
structure.md目录组织
lifecycle.md请求处理流程

Configuration & Setup

配置与初始化

ReferenceWhen to Use
configuration.mdEnvironment, config files
installation.mdNew project setup
upgrade.mdVersion upgrades, breaking changes
releases.mdRelease notes, versioning
参考文档适用场景
configuration.md环境配置、配置文件
installation.md新项目初始化
upgrade.md版本升级、破坏性变更
releases.md发布说明、版本管理

Development Environments

开发环境

ReferenceWhen to Use
sail.mdDocker development
valet.mdmacOS native development
homestead.mdVagrant (legacy)
octane.mdHigh-performance servers
参考文档适用场景
sail.mdDocker开发环境
valet.mdmacOS原生开发环境
homestead.mdVagrant(遗留方案)
octane.md高性能服务器

Utilities & Tools

工具与实用功能

ReferenceWhen to Use
artisan.mdCLI commands, custom commands
helpers.mdGlobal helper functions
filesystem.mdFile storage, S3, local
processes.mdShell command execution
context.mdRequest-scoped data sharing
参考文档适用场景
artisan.mdCLI命令、自定义命令
helpers.md全局辅助函数
filesystem.md文件存储、S3、本地存储
processes.mdShell命令执行
context.md请求作用域数据共享

Advanced Features

高级特性

ReferenceWhen to Use
pennant.mdFeature flags
mcp.mdModel Context Protocol
concurrency.mdParallel execution
参考文档适用场景
pennant.md功能开关
mcp.md模型上下文协议(Model Context Protocol)
concurrency.md并行执行

Operations

运维操作

ReferenceWhen to Use
deployment.mdProduction deployment
envoy.mdSSH task automation
logging.mdLog channels, formatting
errors.mdException handling
packages.mdCreating packages

参考文档适用场景
deployment.md生产环境部署
envoy.mdSSH任务自动化
logging.md日志通道、格式化
errors.md异常处理
packages.md扩展包开发

Templates

模板

TemplatePurpose
UserService.php.mdService + repository pattern
AppServiceProvider.php.mdDI bindings, bootstrapping
ArtisanCommand.php.mdCLI commands, signatures, I/O
McpServer.php.mdMCP servers, tools, resources, prompts
PennantFeature.php.mdFeature flags, A/B testing
Envoy.blade.php.mdSSH deployment automation
sail-config.mdDocker Sail configuration
octane-config.mdFrankenPHP, Swoole, RoadRunner

模板用途
UserService.php.md服务+仓库模式
AppServiceProvider.php.mdDI绑定、初始化
ArtisanCommand.php.mdCLI命令、签名、输入输出
McpServer.php.mdMCP服务器、工具、资源、提示词
PennantFeature.php.md功能开关、A/B测试
Envoy.blade.php.mdSSH部署自动化
sail-config.mdDocker Sail配置
octane-config.mdFrankenPHP、Swoole、RoadRunner配置

Feature Matrix

功能矩阵

FeatureReferencePriority
Service Containercontainer.mdHigh
Service Providersproviders.mdHigh
Directory Structurestructure.mdHigh
Configurationconfiguration.mdHigh
Installationinstallation.mdHigh
Octane (Performance)octane.mdHigh
Sail (Docker)sail.mdHigh
Artisan CLIartisan.mdMedium
Deploymentdeployment.mdMedium
Envoy (SSH)envoy.mdMedium
Facadesfacades.mdMedium
Contractscontracts.mdMedium
Valet (macOS)valet.mdMedium
Upgrade Guideupgrade.mdMedium
Logginglogging.mdMedium
Errorserrors.mdMedium
Lifecyclelifecycle.mdMedium
Filesystemfilesystem.mdMedium
Helpershelpers.mdLow
Pennant (Flags)pennant.mdLow
Contextcontext.mdLow
Processesprocesses.mdLow
Concurrencyconcurrency.mdLow
MCPmcp.mdLow
Packagespackages.mdLow
Releasesreleases.mdLow
Homesteadhomestead.mdLow

功能参考文档优先级
服务容器container.md
服务提供者providers.md
目录结构structure.md
配置configuration.md
初始化installation.md
Octane(性能优化)octane.md
Sail(Docker)sail.md
Artisan CLIartisan.md
部署deployment.md
Envoy(SSH)envoy.md
Facadesfacades.md
契约(Contracts)contracts.md
Valet(macOS)valet.md
升级指南upgrade.md
日志logging.md
错误处理errors.md
请求生命周期lifecycle.md
文件系统filesystem.md
辅助函数helpers.md
Pennant(功能开关)pennant.md
请求上下文context.md
进程管理processes.md
并发执行concurrency.md
MCPmcp.md
扩展包开发packages.md
发布说明releases.md
Homesteadhomestead.md

Quick Reference

快速参考

Service Injection

服务注入

php
public function __construct(
    private readonly UserServiceInterface $userService,
) {}
php
public function __construct(
    private readonly UserServiceInterface $userService,
) {}

Service Provider Binding

服务提供者绑定

php
public function register(): void
{
    $this->app->bind(UserServiceInterface::class, UserService::class);
    $this->app->singleton(CacheService::class);
}
php
public function register(): void
{
    $this->app->bind(UserServiceInterface::class, UserService::class);
    $this->app->singleton(CacheService::class);
}

Artisan Command

Artisan 命令

shell
php artisan make:provider CustomServiceProvider
php artisan make:command ProcessOrders
shell
php artisan make:provider CustomServiceProvider
php artisan make:command ProcessOrders

Environment Access

环境变量访问

php
$debug = env('APP_DEBUG', false);
$config = config('app.name');
php
$debug = env('APP_DEBUG', false);
$config = config('app.name');