導入
DTO は、ビジネス ロジックを含まずにデータ属性をカプセル化する単純なオブジェクトです。これらは、複数のソースからのデータを 1 つのオブジェクトに集約し、管理と送信を容易にするためによく使用されます。 DTO を使用することで、開発者はメソッド呼び出しの数を減らし、パフォーマンスを向上させ、特に分散システムや API でのデータ処理を簡素化できます。
例として、DTO を使用して、HTTP リクエスト経由で受信したデータをマッピングできます。これらの DTO は、受信したペイロード値をそのプロパティに保持し、たとえば、DTO に保持されているデータからデータベースに永続化する準備ができているドクトリン エンティティ オブジェクトを作成することによって、それらをアプリケーション内で使用できます。 DTO データはすでに検証されているため、データベースの永続化中にエラーが発生する可能性を減らすことができます。
MapQueryString 属性と MapRequestPayload 属性
MapQueryString 属性と MapRequestPayload 属性を使用すると、受信したクエリ文字列とペイロード パラメーターをそれぞれマッピングできます。両方の例を見てみましょう。
MapQueryString の例
クエリ文字列内で次のパラメータを受け取ることができる Symfony ルートがあると想像してみましょう:
- from: 必須の開始日
- to: デートするのは必須です
- 年齢: 任意の年齢
上記のパラメータに基づいて、それらを次の 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 ルートがあると想像してみましょう。これらのパラメータは次のとおりです:
- 名前: 必須
- メール: 必須
- 生年月日 (生年月日): 必須
上記のパラメータに基づいて、それらを次の 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 Unprocessable Content 例外をスローします。この種の例外をキャッチし、検証エラーをたとえば 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 中国語 Web サイトの他の関連記事を参照してください。

PHPは動的なWebサイトを構築するために使用され、そのコア関数には次のものが含まれます。1。データベースに接続することにより、動的コンテンツを生成し、リアルタイムでWebページを生成します。 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は、大規模なWebアプリケーションの迅速な開発とメンテナンスに適しています。 2。Pythonは、データサイエンスと機械学習の分野を支配しています。

PHPは、電子商取引、コンテンツ管理システム、API開発で広く使用されています。 1)eコマース:ショッピングカート機能と支払い処理に使用。 2)コンテンツ管理システム:動的コンテンツの生成とユーザー管理に使用されます。 3)API開発:RESTFUL API開発とAPIセキュリティに使用されます。パフォーマンスの最適化とベストプラクティスを通じて、PHPアプリケーションの効率と保守性が向上します。

PHPにより、インタラクティブなWebコンテンツを簡単に作成できます。 1)HTMLを埋め込んでコンテンツを動的に生成し、ユーザー入力またはデータベースデータに基づいてリアルタイムで表示します。 2)プロセスフォームの提出と動的出力を生成して、XSSを防ぐためにHTMLSPECIALCHARSを使用していることを確認します。 3)MySQLを使用してユーザー登録システムを作成し、Password_HashおよびPreprocessingステートメントを使用してセキュリティを強化します。これらの手法を習得すると、Web開発の効率が向上します。

PHPとPythonにはそれぞれ独自の利点があり、プロジェクトの要件に従って選択します。 1.PHPは、特にWebサイトの迅速な開発とメンテナンスに適しています。 2。Pythonは、データサイエンス、機械学習、人工知能に適しており、簡潔な構文を備えており、初心者に適しています。

PHPは依然として動的であり、現代のプログラミングの分野で重要な位置を占めています。 1)PHPのシンプルさと強力なコミュニティサポートにより、Web開発で広く使用されています。 2)その柔軟性と安定性により、Webフォーム、データベース操作、ファイル処理の処理において顕著になります。 3)PHPは、初心者や経験豊富な開発者に適した、常に進化し、最適化しています。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

ドリームウィーバー CS6
ビジュアル Web 開発ツール

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません
