跳到正文
cccskills
免费在 GitHub 公开

acc-layer-arch-knowledge

Layered Architecture knowledge base. Provides patterns, antipatterns, and PHP-specific guidelines for traditional N-tier/Layered Architecture audits.

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(1)

  • SKILL.md10.6 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Layered Architecture Knowledge Base

Quick reference for Layered (N-Tier) Architecture patterns and PHP implementation guidelines.

Core Principles

Layered Architecture Overview

┌─────────────────────────────────────────────────────────────────┐
│                     PRESENTATION LAYER                          │
│         (Controllers, Views, API Endpoints, CLI)                │
│                                                                 │
│  Responsibilities:                                              │
│  - Handle user input                                            │
│  - Display output                                               │
│  - Validate input format                                        │
│  - Route requests                                               │
└───────────────────────────┬─────────────────────────────────────┘
                            │ calls
                            ▼
┌─────────────────────────────────────────────────────────────────┐
│                     APPLICATION LAYER                           │
│           (Services, Use Cases, DTOs, Facades)                  │
│                                                                 │
│  Responsibilities:                                              │
│  - Orchestrate business operations                              │
│  - Transaction management                                       │
│  - Coordinate domain objects                                    │
│  - Map between layers                                           │
└───────────────────────────┬─────────────────────────────────────┘
                            │ calls
                            ▼
┌─────────────────────────────────────────────────────────────────┐
│                      DOMAIN LAYER                               │
│      (Entities, Value Objects, Domain Services, Rules)          │
│                                                                 │
│  Responsibilities:                                              │
│  - Business logic                                               │
│  - Business rules and invariants                                │
│  - Domain events                                                │
│  - Core algorithms                                              │
└───────────────────────────┬─────────────────────────────────────┘
                            │ calls
                            ▼
┌─────────────────────────────────────────────────────────────────┐
│                   INFRASTRUCTURE LAYER                          │
│       (Repositories, External APIs, Database, Cache)            │
│                                                                 │
│  Responsibilities:                                              │
│  - Data persistence                                             │
│  - External service integration                                 │
│  - Technical infrastructure                                     │
│  - Framework-specific code                                      │
└─────────────────────────────────────────────────────────────────┘

Core Rule: Each layer only communicates with the layer directly below it.

Layer Communication Rules

From LayerCan CallCannot Call
PresentationApplicationDomain, Infrastructure
ApplicationDomain, InfrastructurePresentation
DomainInfrastructure (via interfaces)Presentation, Application
Infrastructure—All upper layers

Quick Checklists

Presentation Layer Checklist

  • Controllers are thin
  • No business logic
  • Input validation only
  • Calls application services
  • Transforms output for display
  • Framework code contained here

Application Layer Checklist

  • Orchestrates operations
  • Transaction boundaries
  • No direct DB access
  • Uses domain objects
  • DTOs for input/output
  • No framework dependencies

Domain Layer Checklist

  • Pure business logic
  • No infrastructure code
  • Rich entity behavior
  • Value objects for concepts
  • Business rules encapsulated
  • Repository interfaces only

Infrastructure Layer Checklist

  • Implements domain interfaces
  • Database operations
  • External API calls
  • Caching logic
  • No business logic

Common Violations Quick Reference

ViolationWhere to LookSeverity
Skipping layersController calling DBCritical
Upward dependencyDomain using ApplicationCritical
Business in Controllerif/switch in controllersWarning
Anemic servicesService = simple delegationWarning
Fat repositoryLogic in repositoryWarning

PHP 8.5 Layered Architecture Patterns

Presentation Layer (Controller)

<?php

declare(strict_types=1);

namespace Presentation\Api\Order;

use Application\Order\Service\OrderService;
use Application\Order\DTO\CreateOrderDTO;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

final readonly class OrderController
{
    public function __construct(
        private OrderService $orderService
    ) {}

    public function create(Request $request): JsonResponse
    {
        $dto = CreateOrderDTO::fromRequest($request);

        $result = $this->orderService->createOrder($dto);

        return new JsonResponse($result->toArray(), 201);
    }

    public function show(string $id): JsonResponse
    {
        $order = $this->orderService->getOrder($id);

        return new JsonResponse($order->toArray());
    }
}

Application Layer (Service)

<?php

declare(strict_types=1);

namespace Application\Order\Service;

use Application\Order\DTO\CreateOrderDTO;
use Application\Order\DTO\OrderDTO;
use Domain\Order\Entity\Order;
use Domain\Order\Repository\OrderRepositoryInterface;
use Domain\Order\ValueObject\OrderId;

final readonly class OrderService
{
    public function __construct(
        private OrderRepositoryInterface $orderRepository,
        private TransactionManagerInterface $transactionManager
    ) {}

    public function createOrder(CreateOrderDTO $dto): OrderDTO
    {
        return $this->transactionManager->transactional(function () use ($dto) {
            $order = Order::create(
                id: $this->orderRepository->nextIdentity(),
                customerId: $dto->customerId,
                lines: $dto->lines
            );

            $this->orderRepository->save($order);

            return OrderDTO::fromEntity($order);
        });
    }

    public function getOrder(string $id): OrderDTO
    {
        $order = $this->orderRepository->findById(new OrderId($id));

        if ($order === null) {
            throw new OrderNotFoundException($id);
        }

        return OrderDTO::fromEntity($order);
    }
}

Domain Layer (Entity)

<?php

declare(strict_types=1);

namespace Domain\Order\Entity;

use Domain\Order\ValueObject\OrderId;
use Domain\Order\ValueObject\CustomerId;
use Domain\Order\ValueObject\Money;
use Domain\Order\Enum\OrderStatus;

final class Order
{
    private OrderStatus $status;
    private array $lines = [];

    public function __construct(
        private readonly OrderId $id,
        private readonly CustomerId $customerId
    ) {
        $this->status = OrderStatus::Draft;
    }

    public static function create(OrderId $id, CustomerId $customerId, array $lines): self
    {
        $order = new self($id, $customerId);

        foreach ($lines as $line) {
            $order->addLine($line);
        }

        return $order;
    }

    public function confirm(): void
    {
        if (!$this->canBeConfirmed()) {
            throw new CannotConfirmOrderException();
        }

        $this->status = OrderStatus::Confirmed;
    }

    public function total(): Money
    {
        return array_reduce(
            $this->lines,
            fn (Money $carry, OrderLine $line) => $carry->add($line->total()),
            Money::zero('USD')
        );
    }

    private function canBeConfirmed(): bool
    {
        return $this->status === OrderStatus::Draft && !empty($this->lines);
    }
}

Infrastructure Layer (Repository)

<?php

declare(strict_types=1);

namespace Infrastructure\Persistence\Order;

use Domain\Order\Entity\Order;
use Domain\Order\Repository\OrderRepositoryInterface;
use Domain\Order\ValueObject\OrderId;
use Doctrine\ORM\EntityManagerInterface;

final readonly class DoctrineOrderRepository implements OrderRepositoryInterface
{
    public function __construct(
        private EntityManagerInterface $em
    ) {}

    public function findById(OrderId $id): ?Order
    {
        return $this->em->find(Order::class, $id->value);
    }

    public function save(Order $order): void
    {
        $this->em->persist($order);
        $this->em->flush();
    }

    public function nextIdentity(): OrderId
    {
        return OrderId::generate();
    }
}

References

For detailed information, load these reference files:

  • references/layer-responsibilities.md — Detailed layer responsibilities
  • references/layer-communication.md — Inter-layer communication patterns
  • references/dto-patterns.md — Data Transfer Object patterns
  • references/antipatterns.md — Common violations with detection patterns

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Master backend architectures, REST API design, microservices, and server-side development across multiple languages. Use this as a central index to access specialized sub-skills.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

在每次回复中使用固定前缀并列出本次实际参考的指令/文件,便于校验是否遵循上下文与规则。

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

Automate 21risk tasks via Rube MCP (Composio). Always search tools first for current schemas.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

Automate 2chat tasks via Rube MCP (Composio). Always search tools first for current schemas.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

[00] META. Orchestrate skills into dynamic chains for complex tasks. Analyzes the task, discovers available skills, builds an optimal chain, explains why each skill is needed, and executes step-by-step with user confirmation. Use for any complex task requiring multiple thinking/research/analysis steps. Triggers on "plan this", "how to approach", "what's the strategy", "build a plan", or any multi-step problem requiring skill orchestration.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

查看 MikeCheng1208 的全部技能

报告此技能的问题