Логотип Layered Architecture

Layered Architecture

Спільнота
fatonh
layered-architecture

Use when generating controllers, services, repositories, or DTOs in a Symfony app. Enforces layer boundaries: HTTP in controllers, business logic in services, data access in repositories, and DTO mapping between them. Forbids entities in responses and repository access from controllers.

Огляд

Видавецьfatonh
Репозиторійsymfony-skills
Назва навичкиlayered-architecture
Зірки
36
Форки
3
Файли в пакеті
3
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 3

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: fatonh. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Layered Architecture у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/fatonh/symfony-skills/tree/main/skills/layered-architecture
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/fatonh/symfony-skills.git /tmp/symfony-skills
mkdir -p .claude/skills
cp -r /tmp/symfony-skills/skills/layered-architecture .claude/skills/layered-architecture
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Layered Architecture в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Layered Architecture, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Layered Architecture не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Layered Architecture (Symfony)

Layer rules

Controller (#[Route])     ← HTTP only. No business logic. No entities in responses.
      ↓ DTOs
Service (application)     ← All business logic. Orchestrates repositories. Owns the transaction.
      ↓ Entities / domain objects
Repository (Doctrine)     ← Data access only. No business logic. Returns entities or read models.
      ↓ DQL / DBAL
Database

Dependencies point downward only. A repository never calls a service; a service never sees an Request.

Controller layer

  • Handles HTTP: route matching, deserializing the request, returning a Response.
  • Calls one service method per endpoint — no orchestration in the controller.
  • Never returns a Doctrine entity directly — map to a response DTO (or use serialization groups).
  • Never injects a repository — always go through a service.
  • No try/catch for domain errors — let an exception listener turn them into HTTP responses.
php
// ✅ GOOD
#[Route('/orders', methods: ['POST'])]
public function create(#[MapRequestPayload] CreateOrderRequest $request): JsonResponse
{
    $order = $this->orderService->createOrder($request);

    return $this->json(OrderResponse::fromEntity($order), Response::HTTP_CREATED);
}

// ❌ BAD — business logic + direct repository + entity returned
#[Route('/orders', methods: ['POST'])]
public function create(Request $request, OrderRepository $orders): JsonResponse
{
    $data = json_decode($request->getContent(), true);
    if (empty($data['items'])) {
        throw new \RuntimeException('No items');     // domain rule in controller
    }
    $order = new Order($data);
    $orders->save($order);                            // controller talks to repository
    return $this->json($order);                       // entity leaks out
}

Service layer

  • Contains all business logic, validation rules beyond the DTO, and orchestration.
  • Owns the transaction boundary (EntityManagerInterface::flush() / wrapInTransaction()).
  • Constructor injection only — never ContainerInterface / service locator pulls.
  • One service per aggregate (OrderService, not OrderAndPaymentService).
  • Returns domain objects or DTOs — never an HTTP Request / Response.
php
// ✅ GOOD
final class OrderService
{
    public function __construct(
        private readonly OrderRepository $orders,
        private readonly InventoryService $inventory,
        private readonly EntityManagerInterface $em,
    ) {}

    public function createOrder(CreateOrderRequest $request): Order
    {
        $this->inventory->reserve($request->items);
        $order = Order::create($request->customerEmail);
        foreach ($request->items as $item) {
            $order->addItem($item->productId, $item->quantity);
        }

        $this->em->persist($order);
        $this->em->flush();

        return $order;
    }
}

// ❌ BAD — service container pull, HTTP type in service
final class OrderService
{
    public function __construct(private ContainerInterface $container) {}

    public function createOrder(Request $request): Response { /* ... */ }
}

Repository layer

  • Extends ServiceEntityRepository<Entity>.
  • Custom queries via the query builder or DQL — raw SQL only when unavoidable.
  • Returns entities or read-model DTOs — never associative arrays leaking column names.
  • No business logic — pure data access.
php
// ✅ GOOD
/** @extends ServiceEntityRepository<Order> */
final class OrderRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Order::class);
    }

    /** @return Order[] */
    public function findActiveByCustomer(string $email): array
    {
        return $this->createQueryBuilder('o')
            ->andWhere('o.customerEmail = :email')
            ->andWhere('o.status = :status')
            ->setParameter('email', $email)
            ->setParameter('status', OrderStatus::Active)
            ->getQuery()
            ->getResult();
    }
}

DTOs

  • Separate request and response DTOs — never reuse one class for both.
  • Validation constraints live on the request DTO only (see dto-and-validation).
  • Static factory for mapping: OrderResponse::fromEntity($order).
  • Use readonly classes / promoted readonly properties — DTOs are immutable.
php
// ✅ GOOD
final readonly class OrderResponse
{
    /** @param LineItemResponse[] $items */
    public function __construct(
        public string $id,
        public string $status,
        public array $items,
    ) {}

    public static function fromEntity(Order $order): self
    {
        return new self(
            $order->getId()->toRfc4122(),
            $order->getStatus()->value,
            array_map(LineItemResponse::fromEntity(...), $order->getItems()->toArray()),
        );
    }
}

Mapping

  • Keep mapping out of controllers and services — static factory on the DTO, or a dedicated mapper.
  • Entity → response DTO: OrderResponse::fromEntity($order).
  • Request DTO → entity: static factory on the entity (Order::create(...)) or a mapper service.
  • Collection mapping: array_map(OrderResponse::fromEntity(...), $orders) — first-class callable syntax.

Configuration

  • App wiring lives in config/services.yaml; rely on autowiring + autoconfiguration.
  • Group related settings with #[Autowire] bound parameters or a typed config object — not scattered %env()% reads inside services.
  • Infrastructure-only bean definitions (HTTP clients, factories) go in config/services.yaml, never inside a service class.

Cross-cutting

  • Logging: inject Psr\Log\LoggerInterface — never error_log() / dump() in committed code.
  • Validation: #[MapRequestPayload] validates the DTO automatically; custom rules via constraint validators.
  • Exception handling: one #[AsEventListener(KernelEvents::EXCEPTION)] listener — never try/catch in controllers for domain errors.

Gotchas

  • Agent injects ContainerInterface / uses $this->get() — use constructor injection of the concrete dependency.
  • Agent returns a Doctrine entity from a controller — map to a response DTO (or apply serialization groups).
  • Agent injects a repository into a controller — go through a service.
  • Agent puts flush() and transaction logic in the controller — move it to the service.
  • Agent builds a god service (OrderAndInventoryService) — split by aggregate.
  • Agent decodes JSON manually with json_decode($request->getContent()) — use #[MapRequestPayload] with a DTO.
  • Agent reuses one DTO for request and response — keep them separate.
  • Agent try/catches domain exceptions in the controller — let the exception listener map them.

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ Layered Architecture?

Use when generating controllers, services, repositories, or DTOs in a Symfony app. Enforces layer boundaries: HTTP in controllers, business logic in services, data access in repositories, and DTO mapping between them. Forbids entities in responses and repository access from controllers.

Навіщо використовувати Layered Architecture у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Layered Architecture — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Layered Architecture у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/fatonh/symfony-skills/tree/main/skills/layered-architecture. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Layered Architecture?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Layered Architecture?

Зі скількома забажаєте. У TypingMind ви можете використовувати Layered Architecture із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Layered Architecture?

Так. На GitHub цю навичку публікує fatonh за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇