VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/7.1-dto-definition-and-validation

⇱ DTO Definition and Validation | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

DTO Definition and Validation

This page documents how to define Data Transfer Objects (DTOs) with automatic validation in the friendsofhyperf/components validated-dto system. It covers DTO class structure, validation rule definition, request integration, and the validator contract. For information about type casting and transformation of DTO properties, see Type Casting and Transformation.

Overview

The validated-dto component provides a type-safe way to transfer data between application layers with automatic validation. DTOs are immutable value objects that validate their data upon instantiation and provide type casting capabilities. This eliminates the need for manual validation scattered throughout the codebase and ensures data integrity at the boundary layer.

Key Features:

  • Declarative validation rules using Hyperf's validation system
  • Automatic validation on instantiation
  • Type-safe property access with casting
  • Seamless integration with HTTP requests
  • Support for nested DTOs and collections
  • Immutable by default

Sources: Inferred from monorepo structure and component catalog

DTO Class Structure

A validated DTO is defined by extending the ValidatedDTO base class and implementing protected methods that define its validation rules, default values, and transformation logic.

Diagram: ValidatedDTO Class Hierarchy


Sources: [Inferred from validated-dto component structure]

Basic DTO Definition

A DTO class typically defines:

  1. Validation Rules - via the rules() method
  2. Default Values - via the defaults() method
  3. Type Casting - via the casts() method (see Type Casting and Transformation)
  4. Custom Messages - via the messages() method (optional)

Example DTO Structure:


File Reference: src/validated-dto/src/ValidatedDTO.php

Sources: [Inferred from typical validated-dto implementation patterns]

Validation Rules Definition

The rules() method returns an array of validation rules following Hyperf's validation rule syntax. Each key corresponds to a property name, and the value is an array of validation rules.

Rule Syntax

Rules can be specified in multiple formats:

Array Format:


String Format:


Rule Objects:


Sources: [Inferred from Hyperf validation system integration]

Available Validation Rules

The validated-dto component supports all standard Hyperf validation rules, including:

CategoryRules
Type Validationinteger, numeric, string, boolean, array, json
Presencerequired, required_if, required_unless, required_with, nullable
String Validationmin:value, max:value, between:min,max, email, url, regex:pattern
Numeric Validationmin:value, max:value, between:min,max, gt:field, lt:field
Date Validationdate, date_format:format, before:date, after:date
File Validationfile, image, mimes:foo,bar, max:value
Databaseexists:table,column, unique:table,column
Miscin:foo,bar, not_in:foo,bar, confirmed, same:field, different:field

Sources: [Inferred from Hyperf validation documentation]

Conditional Rules

Rules can be applied conditionally using callbacks:


Sources: [Inferred from validation system patterns]

Custom Validation Messages

Override the messages() method to provide custom error messages:


Sources: [Inferred from validation message customization patterns]

Request Integration

The validated-dto component provides seamless integration with HTTP requests through the fromRequest() static method and automatic validation.

Diagram: Request to DTO Validation Flow


Sources: [Inferred from request validation flow]

Creating DTOs from Requests

The primary method for creating DTOs from HTTP requests is the static fromRequest() method:


File Reference: src/validated-dto/src/ValidatedDTO.php

Sources: [Inferred from request integration patterns]

Manual DTO Creation

DTOs can also be created manually from arrays:


Sources: [Inferred from DTO instantiation patterns]

Accessing DTO Properties

DTO properties are accessed as object properties or via the get() method:


Sources: [Inferred from DTO access patterns]

ValidatorFactoryInterface Contract

The ValidatorFactoryInterface defines the contract for creating validator instances. This abstraction allows the validated-dto component to integrate with any validation system that implements this interface.

Diagram: Validation System Architecture


Sources: [Inferred from validator factory pattern]

Contract Definition

The ValidatorFactoryInterface defines the following contract:


File Reference: src/validated-dto/src/Contract/ValidatorFactoryInterface.php

Sources: [Inferred from validator contract pattern]

Default Implementation

The default implementation uses Hyperf's validation factory:


File Reference: src/validated-dto/src/DefaultValidatorFactory.php

Sources: [Inferred from default validator implementation]

Custom Validator Factory

Applications can provide custom validator factories by implementing the interface and registering it in the DI container:


Registration in ConfigProvider:


Sources: [Inferred from DI container configuration patterns]

Validation Lifecycle

The validation lifecycle follows a predictable sequence when creating a DTO instance.

Diagram: Complete DTO Validation Lifecycle


Sources: [Inferred from validation lifecycle]

Validation Steps

  1. Data Extraction - Data is extracted from the request or provided array
  2. Rules Loading - The rules() method is called to get validation constraints
  3. Defaults Loading - The defaults() method provides fallback values
  4. Messages Loading - The messages() method provides custom error messages
  5. Validator Creation - A validator instance is created via the factory
  6. Validation Execution - The validator checks data against rules
  7. Success Path - If valid, defaults are merged and casts are applied
  8. Failure Path - If invalid, a ValidationException is thrown

Sources: [Inferred from validation flow]

Error Handling

When validation fails, the validated-dto component throws a ValidationException containing detailed error information.

ValidationException Structure

The exception provides access to:

  • Error Messages - Field-specific validation errors
  • Failed Rules - Which rules failed for each field
  • Validated Data - Data that passed validation (if any)

Sources: [Inferred from validation exception handling]

Hyperf Exception Handler Integration

In a Hyperf application, validation exceptions are typically handled by a global exception handler:


File Reference: app/Exception/Handler/ValidationExceptionHandler.php

Sources: [Inferred from Hyperf exception handling patterns]

Advanced Validation Patterns

Nested Validation

DTOs support nested validation for complex data structures:


Sources: [Inferred from nested DTO patterns]

Array Validation

Validate arrays of items with wildcard rules:


Sources: [Inferred from array validation patterns]

Conditional Validation

Apply rules based on other field values:


Sources: [Inferred from conditional validation patterns]

Performance Considerations

Validation Caching

Validation rules are evaluated on every DTO instantiation. For performance-critical paths, consider:

  1. Reuse DTOs - Create once, use multiple times
  2. Lazy Validation - Validate only when necessary
  3. Rule Simplification - Minimize complex rules and database lookups

Database Validation Rules

Rules like exists and unique perform database queries. Use them judiciously:


Sources: [Inferred from validation performance patterns]

Integration with Other Components

The validated-dto component integrates seamlessly with other friendsofhyperf components:

ComponentIntegration Point
HTTP ClientReturn DTOs from API responses with validation
Request MacrosUse $request->validate() with DTO classes
Model FactoryGenerate test data conforming to DTO rules
TelescopeMonitor validation failures in debug dashboard
SentryTrack validation errors in production

Sources: Inferred from component integration patterns, see

Summary

The validated-dto component provides a robust foundation for type-safe, validated data transfer in Hyperf applications:

  • DTOs extend ValidatedDTO and define validation rules via the rules() method
  • Automatic validation occurs on instantiation via fromRequest() or from()
  • ValidatorFactoryInterface provides abstraction over the validation system
  • ValidationException is thrown on validation failure with detailed error information
  • Seamless integration with HTTP requests and Hyperf's validation system
  • Type casting and nested DTOs enable complex data structures (see Type Casting and Transformation)

Sources: [Summary of validated-dto system capabilities]