Skip to content

分层设计

MineShop 采用四层架构,各层职责清晰,依赖关系单向。

🎯 分层结构

┌─────────────────────────────────────────────────────────────┐
│                    Interface 接口层                          │
│                    ↓ 依赖 ↓                                  │
├─────────────────────────────────────────────────────────────┤
│                   Application 应用层                         │
│                    ↓ 依赖 ↓                                  │
├─────────────────────────────────────────────────────────────┤
│                     Domain 领域层                            │
│                    ↓ 依赖 ↓                                  │
├─────────────────────────────────────────────────────────────┤
│                  Infrastructure 基础设施层                    │
└─────────────────────────────────────────────────────────────┘

📦 各层职责

1. Interface 接口层

负责处理外部请求,包括 HTTP、RPC、CLI 等。

php
// app/Interface/Admin/Controller/Order/OrderController.php
#[Controller(prefix: '/admin/order')]
class OrderController extends AbstractController
{
    #[PostMapping('')]
    public function create(CreateOrderRequest $request): ResponseInterface
    {
        $result = $this->appOrderService->create(
            new CreateOrderDto($request->validated())
        );
        return $this->success($result);
    }
}

职责:

  • 接收和验证请求参数
  • 调用应用服务
  • 返回响应结果
  • 异常处理和转换

2. Application 应用层

编排业务流程,协调领域服务。

php
// app/Application/Admin/Order/AppOrderCommandService.php
class AppOrderCommandService
{
    public function create(CreateOrderDto $dto): Order
    {
        // 1. DTO → Entity
        $entity = OrderMapper::fromDto($dto);
        
        // 2. 调用领域服务
        $order = $this->domainOrderService->create($entity);
        
        // 3. 发送通知
        $this->notificationService->sendOrderCreated($order);
        
        return $order;
    }
}

职责:

  • DTO 与 Entity 转换
  • 事务管理
  • 跨领域协调
  • 发送通知/事件

3. Domain 领域层

核心业务逻辑所在,不依赖任何框架。

php
// app/Domain/Trade/Order/Service/DomainOrderService.php
class DomainOrderService
{
    public function create(OrderEntity $entity): Order
    {
        // 业务规则校验
        $entity->validate();
        
        // 库存预扣
        $this->stockService->reserve($entity->getItems());
        
        // 持久化
        return $this->repository->save($entity);
    }
}

职责:

  • 业务规则实现
  • 领域事件发布
  • 聚合根管理
  • 领域服务编排

4. Infrastructure 基础设施层

提供技术实现,包括数据库、缓存、消息队列等。

php
// app/Infrastructure/Model/Order/Order.php
class Order extends Model
{
    protected $table = 'orders';
    protected $fillable = ['order_no', 'member_id', 'status'];
}

职责:

  • 数据持久化
  • 缓存实现
  • 消息队列
  • 外部服务集成

🔄 依赖规则

层级可依赖不可依赖
InterfaceApplication, Domain, Infrastructure-
ApplicationDomain, InfrastructureInterface
DomainInfrastructure (接口)Interface, Application
Infrastructure-Interface, Application, Domain

✅ 最佳实践

  1. 单向依赖: 上层依赖下层,禁止反向依赖
  2. 接口隔离: 领域层通过接口依赖基础设施
  3. 职责单一: 每层只做自己该做的事
  4. 测试友好: 各层可独立测试

📚 相关文档

基于 Apache-2.0 许可发布 | 感谢 MineAdmin 提供的优秀基础框架