Logo di Layered Architecture

Layered Architecture

Community
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.

Panoramica

Autorefatonh
Repositorysymfony-skills
Nome della skilllayered-architecture
Stelle
36
Fork
3
File inclusi
3
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • 3 file inclusi

    Script, modelli di documento e riferimenti che il modello può leggere mentre lavora. I file sono di sola lettura e non vengono mai eseguiti.

  • Open source

    Pubblicata da fatonh su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Layered Architecture in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/fatonh/symfony-skills/tree/main/skills/layered-architecture
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Nuova skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella nella cartella delle skill di quell'agente.

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
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Layered Architecture in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Layered Architecture non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Layered Architecture non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

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.

File inclusi

Il modello legge questi file quando servono, mentre la skill è caricata. Sono accessibili in sola lettura e non vengono mai eseguiti.

Domande frequenti

Cosa fa la skill IA 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.

Perché usare Layered Architecture su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Layered Architecture è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Layered Architecture in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/fatonh/symfony-skills/tree/main/skills/layered-architecture. TypingMind legge il file SKILL.md, include i file associati e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Layered Architecture?

Qualsiasi modello che colleghi in TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Layered Architecture?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Layered Architecture: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Layered Architecture è gratuita?

Sì. È pubblicata su GitHub da fatonh con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, modelli o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇