소개
DTO는 비즈니스 로직을 포함하지 않고 데이터 속성을 캡슐화하는 간단한 개체입니다. 여러 소스의 데이터를 단일 개체로 집계하는 데 자주 사용되므로 관리 및 전송이 더 쉬워집니다. DTO를 사용하면 개발자는 특히 분산 시스템이나 API에서 메소드 호출 수를 줄이고 성능을 향상시키며 데이터 처리를 단순화할 수 있습니다.
예를 들어 DTO를 사용하여 HTTP 요청을 통해 수신된 데이터를 매핑할 수 있습니다. 해당 DTO는 수신된 페이로드 값을 해당 속성에 보유하고 애플리케이션 내에서 이를 사용할 수 있습니다. 예를 들어 DTO에 보관된 데이터에서 데이터베이스에 유지할 준비가 된 교리 엔터티 개체를 생성합니다. DTO 데이터는 이미 검증되었으므로 데이터베이스가 유지되는 동안 오류가 발생할 가능성을 줄일 수 있습니다.
MapQueryString 및 MapRequestPayload 속성
MapQueryString 및 MapRequestPayload 속성을 사용하면 수신된 쿼리 문자열과 페이로드 매개변수를 각각 매핑할 수 있습니다. 두 가지 모두의 예를 살펴보겠습니다.
MapQueryString 예
쿼리 문자열 내에서 다음 매개변수를 수신할 수 있는 Symfony 경로가 있다고 가정해 보겠습니다.
- from: 필수 from 날짜
- to: 필수 데이트
- age: 선택적 연령
위 매개변수를 기반으로 다음 dto에 매핑하려고 합니다.
readonly class QueryInputDto { public function __construct( #[Assert\Datetime(message: 'From must be a valid datetime')] #[Assert\NotBlank(message: 'From date cannot be empty')] public string $from, #[Assert\Datetime(message: 'To must be a valid datetime')] #[Assert\NotBlank(message: 'To date cannot be empty')] public string $to, public ?int $age = null ){} }
이를 매핑하려면 다음과 같은 방법으로 MapQueryString 속성만 사용해야 합니다.
#[Route('/my-get-route', name: 'my_route_name', methods: ['GET'])] public function myAction(#[MapQueryString] QueryInputDTO $queryInputDto) { // your code }
보시다시피, Symfony는 $queryInputDto 인수가 #[MapQueryString] 속성으로 플래그 지정되었음을 감지하면 수신된 쿼리 문자열 매개변수를 해당 인수에 자동으로 매핑합니다. QueryInputDTO 클래스.
MapRequestPayload 예시
이 경우 JSON 요청 페이로드 내에서 새 사용자를 등록하는 데 필요한 데이터를 수신하는 Symfony 경로가 있다고 가정해 보겠습니다. 해당 매개변수는 다음과 같습니다.
- 이름: 필수
- 이메일: 필수
- 생년월일(dob): 필수
위 매개변수를 기반으로 다음 dto에 매핑하려고 합니다.
readonly class PayloadInputDto { public function __construct( #[Assert\NotBlank(message: 'Name cannot be empty')] public string $name, #[Assert\NotBlank(message: 'Email cannot be empty')] #[Assert\Email(message: 'Email must be a valid email')] public string $email, #[Assert\NotBlank(message: 'From date cannot be empty')] #[Assert\Date(message: 'Dob must be a valid date')] public ?string $dob = null ){} }
매핑하려면 다음과 같이 MapRequestPayload 속성만 사용해야 합니다.
#[Route('/my-post-route', name: 'my_post_route', methods: ['POST'])] public function myAction(#[MapRequestPayload] PayloadInputDTO $payloadInputDto) { // your code }
이전 섹션에서 살펴본 것처럼 Symfony는 $payloadInputDto 인수가 #[MapRequestPayload] 속성으로 플래그 지정되었음을 감지하면 수신된 페이로드 매개변수를 해당 인수에 자동으로 매핑합니다. PayloadInputDTO 클래스
의 인스턴스MapRequestPayload는 JSON 페이로드와 양식 URL로 인코딩된 페이로드 모두에서 작동합니다.
DTO 유효성 검사 오류 처리
매핑 프로세스 중에 유효성 검사가 실패하는 경우(예: 필수 이메일이 전송되지 않은 경우) Symfony는 422 처리할 수 없는 콘텐츠 예외를 발생시킵니다. 이러한 종류의 예외를 포착하고 클라이언트에 json과 같은 유효성 검사 오류를 반환하려면 이벤트 구독자를 생성하고 KernelException 이벤트를 계속 수신 대기하면 됩니다.
class KernelSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ KernelEvents::EXCEPTION => 'onException' ]; } public function onException(ExceptionEvent $event): void { $exception = $event->getThrowable(); if($exception instanceof UnprocessableEntityHttpException) { $previous = $exception->getPrevious(); if($previous instanceof ValidationFailedException) { $errors = []; foreach($previous->getViolations() as $violation) { $errors[] = [ 'path' => $violation->getPropertyPath(), 'error' => $violation->getMessage() ]; } $event->setResponse(new JsonResponse($errors)); } } } }
onException 메서드가 트리거된 후 이벤트 예외가 UnprocessableEntityHttpException의 인스턴스인지 확인합니다. 그렇다면 이전 예외가 ValidationFailedException 클래스의 인스턴스인지 확인하면서 처리할 수 없는 오류가 실패한 유효성 검사에서 발생한 것인지도 확인합니다. 그렇다면 모든 위반 오류를 배열에 저장하고(속성 경로만 키로, 위반 메시지만 오류로) 이러한 오류로부터 JSON 응답을 생성하고 이벤트에 새 응답을 설정합니다.
다음 이미지는 이메일이 전송되지 않아 실패한 요청에 대한 JSON 응답을 보여줍니다.
@baseUrl = http://127.0.0.1:8000 POST {{baseUrl}}/my-post-route Content-Type: application/json { "name" : "Peter Parker", "email" : "", "dob" : "1990-06-28" } ------------------------------------------------------------- HTTP/1.1 422 Unprocessable Entity Cache-Control: no-cache, private Content-Type: application/json Date: Fri, 20 Sep 2024 16:44:20 GMT Host: 127.0.0.1:8000 X-Powered-By: PHP/8.2.23 X-Robots-Tag: noindex Transfer-Encoding: chunked [ { "path": "email", "error": "Email cannot be empty" } ]
위 이미지 요청은 http 파일을 사용하여 생성되었습니다.
사용자 정의 리졸버 만들기
쿼리 문자열 매개변수를 "f"라는 배열로 수신하는 경로가 있다고 가정해 보겠습니다. 다음과 같습니다:
/my-get-route?f[from]=2024-08-20 16:24:08&f[to]=&f[age]=14
요청에서 해당 배열을 확인한 다음 데이터의 유효성을 검사하는 사용자 지정 확인자를 만들 수 있습니다. 코딩해 보겠습니다.
use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Attribute\MapQueryString; use Symfony\Component\HttpKernel\Controller\ValueResolverInterface; use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent; use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Validator\Exception\ValidationFailedException; use Symfony\Component\Validator\Validator\ValidatorInterface; class CustomQsValueResolver implements ValueResolverInterface, EventSubscriberInterface { public function __construct( private readonly ValidatorInterface $validator, private readonly SerializerInterface $serializer ){} public static function getSubscribedEvents(): array { return [ KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments', ]; } public function resolve(Request $request, ArgumentMetadata $argument): iterable { $attribute = $argument->getAttributesOfType(MapQueryString::class, ArgumentMetadata::IS_INSTANCEOF)[0] ?? null; if (!$attribute) { return []; } if ($argument->isVariadic()) { throw new \LogicException(sprintf('Mapping variadic argument "$%s" is not supported.', $argument->getName())); } $attribute->metadata = $argument; return [$attribute]; } public function onKernelControllerArguments(ControllerArgumentsEvent $event): void { $arguments = $event->getArguments(); $request = $event->getRequest(); foreach ($arguments as $i => $argument) { if($argument instanceof MapQueryString ) { $qs = $request->get('f', []); if(count($qs) > 0) { $object = $this->serializer->denormalize($qs, $argument->metadata->getType()); $violations = $this->validator->validate($object); if($violations->count() > 0) { $validationFailedException = new ValidationFailedException(null, $violations); throw new UnprocessableEntityHttpException('Unale to process received data', $validationFailedException); } $arguments[$i] = $object; } } } $event->setArguments($arguments); } }
The CustomQsValueResolver implements the ValueResolverInterface and the EventSubscriberInterface, allowing it to resolve arguments for controller actions and listen to specific events in the Symfony event system. In this case, the resolver listens to the Kernel CONTROLLER_ARGUMENTS event.
Let's analyze it step by step:
The constructor
The constructor takes two dependencies: The Validator service for validating objects and a the Serializer service for denormalizing data into objects.
The getSubscribedEvents method
The getSubscribedEvents method returns an array mapping the KernelEvents::CONTROLLER_ARGUMENTS symfony event to the onKernelControllerArguments method. This means that when the CONTROLLER_ARGUMENTS event is triggered (always a controller is reached), the onKernelControllerArguments method will be called.
The resolve method
The resolve method is responsible for resolving the value of an argument based on the request and its metadata.
- It checks if the argument has the MapQueryString attribute. If not, it returns an empty array.
- If the argument is variadic, that is, it can accept a variable number of arguments, it throws a LogicException, indicating that mapping variadic arguments is not supported.
- If the attribute is found, it sets the metadata property of the attribute and returns it as a php iterable.
The onKernelControllerArguments method
The onKernelControllerArguments method is called when the CONTROLLER_ARGUMENTS event is triggered.
- It retrieves the current arguments and the request from the event.
- It iterates over the arguments, checking for arguments flagged as MapQueryString
- If found, it retrieves the query string parameters holded by the "f" array using $request->get('f', []).
- If there are parameters, it denormalizes them into an object of the type specified in the argument's metadata (The Dto class).
- It then validates the object using the validator. If there are validation violations, it throws an UnprocessableEntityHttpException which wraps a ValidationFailedException with the validation errors.
- If validation passes, it replaces the original argument with the newly created object.
Using the resolver in the controller
To instruct the MapQueryString attribute to use our recently created resolver instead of the default one, we must specify it with the attribute resolver value. Let's see how to do it:
#[Route('/my-get-route', name: 'my_route_name', methods: ['GET'])] public function myAction(#[MapQueryString(resolver: CustomQsValueResolver::class)] QueryInputDTO $queryInputDto) { // your code }
Conclusion
In this article, we have analized how symfony makes our lives easier by making common application tasks very simple, such as receiving and validating data from an API. To do that, it offers us the MapQueryString and MapRequestPayload attributes. In addition, it also offers us the possibility of creating our custom mapping resolvers for cases that require specific needs.
If you like my content and enjoy reading it and you are interested in learning more about PHP, you can read my ebook about how to create an operation-oriented API using PHP and the Symfony Framework. You can find it here: Building an Operation-Oriented Api using PHP and the Symfony Framework: A step-by-step guide
위 내용은 Symfony 속성을 사용하여 DTO를 검증하는 쉬운 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PHP는 동적 웹 사이트를 구축하는 데 사용되며 해당 핵심 기능에는 다음이 포함됩니다. 1. 데이터베이스와 연결하여 동적 컨텐츠를 생성하고 웹 페이지를 실시간으로 생성합니다. 2. 사용자 상호 작용 및 양식 제출을 처리하고 입력을 확인하고 작업에 응답합니다. 3. 개인화 된 경험을 제공하기 위해 세션 및 사용자 인증을 관리합니다. 4. 성능을 최적화하고 모범 사례를 따라 웹 사이트 효율성 및 보안을 개선하십시오.

PHP는 MySQLI 및 PDO 확장 기능을 사용하여 데이터베이스 작업 및 서버 측 로직 프로세싱에서 상호 작용하고 세션 관리와 같은 기능을 통해 서버 측로 로직을 처리합니다. 1) MySQLI 또는 PDO를 사용하여 데이터베이스에 연결하고 SQL 쿼리를 실행하십시오. 2) 세션 관리 및 기타 기능을 통해 HTTP 요청 및 사용자 상태를 처리합니다. 3) 트랜잭션을 사용하여 데이터베이스 작업의 원자력을 보장하십시오. 4) SQL 주입 방지, 디버깅을 위해 예외 처리 및 폐쇄 연결을 사용하십시오. 5) 인덱싱 및 캐시를 통해 성능을 최적화하고, 읽을 수있는 코드를 작성하고, 오류 처리를 수행하십시오.

PHP에서 전처리 문과 PDO를 사용하면 SQL 주입 공격을 효과적으로 방지 할 수 있습니다. 1) PDO를 사용하여 데이터베이스에 연결하고 오류 모드를 설정하십시오. 2) 준비 방법을 통해 전처리 명세서를 작성하고 자리 표시자를 사용하여 데이터를 전달하고 방법을 실행하십시오. 3) 쿼리 결과를 처리하고 코드의 보안 및 성능을 보장합니다.

PHP와 Python은 고유 한 장점과 단점이 있으며 선택은 프로젝트 요구와 개인 선호도에 달려 있습니다. 1.PHP는 대규모 웹 애플리케이션의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 데이터 과학 및 기계 학습 분야를 지배합니다.

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP를 사용하면 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다. 1) HTML을 포함하여 컨텐츠를 동적으로 생성하고 사용자 입력 또는 데이터베이스 데이터를 기반으로 실시간으로 표시합니다. 2) 프로세스 양식 제출 및 동적 출력을 생성하여 htmlspecialchars를 사용하여 XSS를 방지합니다. 3) MySQL을 사용하여 사용자 등록 시스템을 작성하고 Password_Hash 및 전처리 명세서를 사용하여 보안을 향상시킵니다. 이러한 기술을 마스터하면 웹 개발의 효율성이 향상됩니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

드림위버 CS6
시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
