Logo Dto And Validation

Dto And Validation

Cộng đồng
fatonh
dto-and-validation

Use when creating request/response DTOs, applying Symfony Validator constraints, mapping payloads with #[MapRequestPayload]/#[MapQueryString], or mapping DTOs to/from entities. Use when the task mentions DTO, request validation, form input, or the Validator component.

Tổng quan

Nhà phát hànhfatonh
Kho mãsymfony-skills
Tên kỹ năngdto-and-validation
Sao
36
Bản fork
3
Tệp đi kèm
1
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 1 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được fatonh công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Dto And Validation trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/fatonh/symfony-skills/tree/main/skills/dto-and-validation
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

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/dto-and-validation .claude/skills/dto-and-validation
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Dto And Validation trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Dto And Validation ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Dto And Validation với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

DTOs & Validation (Symfony)

DTOs are immutable, typed, and split by direction

  • Request DTO — carries input, holds validation constraints, never touches the DB.
  • Response DTO — carries output, has a fromEntity() factory, no constraints.
  • Never reuse one class for both directions.
  • Use readonly promoted properties; default empty collections to [], never null.
php
// ✅ Request DTO — constraints live here
final class CreateOrderRequest
{
    public function __construct(
        #[Assert\NotBlank]
        #[Assert\Email]
        public readonly string $customerEmail = '',

        /** @var CreateLineRequest[] */
        #[Assert\Valid]                          // cascade into nested DTOs
        #[Assert\Count(min: 1, minMessage: 'An order needs at least one line.')]
        public readonly array $items = [],
    ) {}
}

final class CreateLineRequest
{
    public function __construct(
        #[Assert\NotBlank]
        #[Assert\Uuid]
        public readonly string $productId = '',

        #[Assert\Positive]
        public readonly int $quantity = 0,
    ) {}
}
php
// ✅ Response DTO — no constraints, has a factory
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()),
        );
    }
}

#[MapRequestPayload] does deserialization + validation

Don't decode JSON manually and don't call the validator yourself in the controller. The attribute handles both; on failure it throws ValidationFailedException → your exception listener returns 422 (see problem-details-rfc9457).

php
#[Route('/api/orders', methods: ['POST'])]
public function create(#[MapRequestPayload] CreateOrderRequest $request): JsonResponse
{
    // $request is already deserialized AND validated here.
    $order = $this->orderService->createOrder($request);
    return $this->json(OrderResponse::fromEntity($order), Response::HTTP_CREATED);
}

// Query strings -> DTO
public function list(#[MapQueryString] OrderListQuery $query): JsonResponse { /* ... */ }
php
// ❌ BAD — manual decode + manual validate + manual error response in the controller
public function create(Request $request, ValidatorInterface $validator): JsonResponse
{
    $dto = $this->serializer->deserialize($request->getContent(), CreateOrderRequest::class, 'json');
    $errors = $validator->validate($dto);
    if (count($errors) > 0) {
        return $this->json(['errors' => (string) $errors], 400); // ad-hoc, wrong status
    }
    // ...
}

Built-in constraints over custom code

Reach for the standard constraints before writing logic:

NotBlank, NotNull, Length, Range, Positive, PositiveOrZero, Email, Uuid, Choice, Count, Valid (cascade), Type, GreaterThan, Regex, When (conditional), Unique.

php
#[Assert\Choice(callback: [OrderStatus::class, 'values'])]
public readonly string $status;

#[Assert\When(
    expression: 'this.shippingRequired === true',
    constraints: [new Assert\NotBlank()],
)]
public readonly ?string $shippingAddress = null;

Custom constraints when a rule repeats

For domain rules used in more than one place, write a constraint + validator rather than inlining checks.

php
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final class UniqueCustomerEmail extends Constraint
{
    public string $message = 'An account with email "{{ value }}" already exists.';
}

final class UniqueCustomerEmailValidator extends ConstraintValidator
{
    public function __construct(private readonly CustomerRepository $customers) {}

    public function validate(mixed $value, Constraint $constraint): void
    {
        if ($value === null || $value === '') {
            return; // let NotBlank handle emptiness
        }
        if ($this->customers->existsByEmail($value)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', (string) $value)
                ->addViolation();
        }
    }
}

Complex & nested payloads

Real APIs rarely take a flat object. The rules below keep deep/nested JSON validating correctly.

#[Assert\Valid] must repeat at every level

Validation does not recurse automatically. Each property that holds a nested DTO (object or array of objects) needs its own #[Assert\Valid], all the way down — miss one and the constraints inside that branch silently don't run.

php
final class CreateOrderRequest
{
    public function __construct(
        #[Assert\NotBlank, Assert\Email]
        public readonly string $customerEmail = '',

        #[Assert\Valid]                              // cascade into the address object
        public readonly ?AddressRequest $shippingAddress = null,

        /** @var OrderLineRequest[] */
        #[Assert\Valid]                              // cascade into EACH array element
        #[Assert\Count(min: 1)]
        public readonly array $items = [],
    ) {}
}

final class OrderLineRequest
{
    public function __construct(
        #[Assert\Uuid]
        public readonly string $productId = '',

        #[Assert\Positive]
        public readonly int $quantity = 0,

        /** @var DiscountRequest[] */
        #[Assert\Valid]                              // still required two levels deep
        public readonly array $discounts = [],
    ) {}
}

Typed nested DTOs deserialize automatically

The Serializer hydrates nested DTOs from the property type hint — no manual wiring. Type the property as the DTO (or DtoType[] via the @var PHPDoc for arrays) and #[MapRequestPayload] builds the whole graph.

php
// JSON: { "customerEmail": "...", "shippingAddress": { "city": "..." }, "items": [ { ... } ] }
public function create(#[MapRequestPayload] CreateOrderRequest $request): JsonResponse
// $request->shippingAddress is an AddressRequest; $request->items is OrderLineRequest[]

For arrays of objects you must give the @var ItemType[] PHPDoc — the Serializer needs it to know what to hydrate each element into; without it you get an array of stdClass/arrays and the nested constraints never fire.

Polymorphic / discriminated payloads

When a field can be one of several shapes ({"type": "card", ...} vs {"type": "paypal", ...}), use a #[DiscriminatorMap] on an abstract base so the Serializer picks the right concrete DTO.

php
#[DiscriminatorMap(typeProperty: 'type', mapping: [
    'card'   => CardPaymentRequest::class,
    'paypal' => PaypalPaymentRequest::class,
])]
abstract class PaymentRequest {}

final class CardPaymentRequest extends PaymentRequest
{
    public function __construct(
        #[Assert\CardScheme(Assert\CardScheme::VISA)]
        public readonly string $pan = '',
    ) {}
}

When #[MapRequestPayload] isn't enough → a custom ValueResolver

#[MapRequestPayload] deserializes one DTO from the body. When you need to build a DTO from several request parts (body + route params + headers), apply non-trivial pre-processing, or support a payload shape the Serializer can't express, write a ValueResolverInterface instead of decoding in the controller.

php
final class CreateOrderRequestResolver implements ValueResolverInterface
{
    public function __construct(
        private readonly SerializerInterface $serializer,
        private readonly ValidatorInterface $validator,
    ) {}

    /** @return iterable<CreateOrderRequest> */
    public function resolve(Request $request, ArgumentMetadata $argument): iterable
    {
        if ($argument->getType() !== CreateOrderRequest::class) {
            return [];
        }

        $dto = $this->serializer->deserialize($request->getContent(), CreateOrderRequest::class, 'json');

        // Enrich from other request parts the body doesn't carry.
        $dto = $dto->withTenantId($request->attributes->get('tenantId'));

        $violations = $this->validator->validate($dto);
        if (\count($violations) > 0) {
            throw new ValidationFailedException($dto, $violations); // -> 422 via the exception listener
        }

        yield $dto;
    }
}
php
// Controller stays thin — the resolver does the work, just like #[MapRequestPayload].
public function create(CreateOrderRequest $request): JsonResponse { /* ... */ }

Throw ValidationFailedException (not an ad-hoc response) so your problem-details listener still produces consistent 422 output. Reserve custom resolvers for cases the attribute genuinely can't handle — don't reimplement #[MapRequestPayload].

Limit nesting depth on untrusted input

Deeply nested JSON is a denial-of-service vector. Cap depth at the edge (json_decode($json, depth: 32) semantics) or via the Serializer's json_decode_options/max_depth context, and keep payloads shallow by design.

OpenAPI / contract-first: if you generate or hand-maintain an OpenAPI schema, keep the DTO and the schema in lockstep so the documented contract matches what's actually validated. With API Platform the schema is generated from the resource/DTO automatically — see the api-platform-resources skill.

Mapping DTO → entity

Keep mapping out of controllers. Construct the entity through its factory/behavior methods (see domain-driven-design), passing scalar values from the DTO. Don't blindly hydrate an entity from request data — that's how mass-assignment bugs happen.

php
// In the service
$order = Order::create($request->customerEmail);
foreach ($request->items as $line) {
    $order->addItem(Uuid::fromString($line->productId), $line->quantity);
}

Gotchas

  • Agent reuses one class for request and response — split them; constraints belong only on the request DTO.
  • Agent decodes JSON and calls $validator->validate() by hand in the controller — use #[MapRequestPayload].
  • Agent returns 400 for validation errors with ad-hoc JSON — let the exception listener produce 422 problem+json.
  • Agent forgets #[Assert\Valid] on nested DTO arrays — nested constraints won't run without it.
  • Agent adds #[Assert\Valid] at the top level but not on deeper nested DTOs — cascade doesn't recurse; repeat it at every level.
  • Agent omits the @var ItemType[] PHPDoc on an array property — the Serializer hydrates stdClass/arrays and nested validation never fires.
  • Agent hand-writes if ($data['type'] === 'card') branching for polymorphic payloads — use #[DiscriminatorMap] and concrete DTO subclasses.
  • Agent decodes the body in the controller when the DTO needs data from route/headers too — write a ValueResolverInterface instead.
  • Agent's custom resolver returns an ad-hoc error response — throw ValidationFailedException so the problem-details listener produces a consistent 422.
  • Agent leaves nesting depth unbounded on public input — cap decode depth to avoid a DoS vector.
  • Agent writes manual if (empty(...)) checks in the service for things constraints already cover.
  • Agent hydrates a Doctrine entity directly from request data (mass assignment) — go through the entity's factory/behavior methods.
  • Agent puts validation on the entity instead of the request DTO — entities enforce invariants; DTOs validate input shape.
  • Agent makes DTO properties nullable + mutable — prefer readonly with sensible defaults.

Tệp đi kèm

Khi kỹ năng đã được tải, mô hình có thể đọc các tệp này nếu cần. Các tệp này chỉ dùng để đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Dto And Validation làm được gì?

Use when creating request/response DTOs, applying Symfony Validator constraints, mapping payloads with #[MapRequestPayload]/#[MapQueryString], or mapping DTOs to/from entities. Use when the task mentions DTO, request validation, form input, or the Validator component.

Vì sao nên dùng Dto And Validation trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Dto And Validation là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Dto And Validation trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/fatonh/symfony-skills/tree/main/skills/dto-and-validation. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm rồi cài đặt cả gói dưới dạng một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Dto And Validation?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Dto And Validation với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Dto And Validation với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Dto And Validation có miễn phí không?

Có. Kỹ năng này được fatonh phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇