VOOZH about

URL: https://deepwiki.com/hypervel/validation/5.1-creating-validators

⇱ Creating Validators | hypervel/validation | DeepWiki


Loading...
Menu

Creating Validators

This page documents the different methods for instantiating Validator instances in the Hypervel Validation package. It covers direct instantiation via the constructor, factory-based creation, and dependency injection patterns used within the Hyperf framework.

For information about customizing validator behavior through extensions and custom validation methods, see Extensions and Customization. For details about the underlying Validator class structure and lifecycle, see Validator Class.


Overview

The Hypervel Validation package provides multiple approaches for creating validator instances, each suited to different use cases:

  1. Direct Instantiation - Manually constructing Validator objects
  2. Factory Pattern - Using the Factory class to create validators with proper dependencies
  3. Dependency Injection - Leveraging Hyperf's DI container to automatically resolve factory instances

The recommended approach for most applications is to use the Factory class through dependency injection, as it ensures proper configuration and dependency resolution.

Sources: src/Validator.php284-305 src/ValidatorFactory.php13-29


Validator Constructor

The Validator class can be instantiated directly by calling its constructor. This approach requires manual dependency management but provides full control over validator configuration.

Constructor Signature

The Validator constructor accepts five parameters:

ParameterTypeRequiredDescription
$translatorTranslatorYesTranslation service for error messages
$dataarrayYesData to be validated
$rulesarrayYesValidation rules to apply
$messagesarrayNoCustom error messages (default: [])
$attributesarrayNoCustom attribute names for display (default: [])

Constructor Behavior

The constructor performs several initialization tasks:

  1. Placeholder Hash Generation - Generates a random hash for escaping dots and asterisks in attribute names (src/Validator.php295-297)
  2. Data Parsing - Converts data keys by replacing dots and asterisks with placeholder strings (src/Validator.php301 src/Validator.php310-330)
  3. Rule Storage - Stores initial rules and sets them through setRules() (src/Validator.php299-304)
  4. Custom Configuration - Applies custom messages and attribute names (src/Validator.php300-302)

Example: Direct Instantiation


Sources: src/Validator.php284-305


Factory-Based Creation

The Factory class provides a higher-level interface for creating validators with automatic dependency injection and configuration. While the Factory class itself is not shown in the provided files, the ValidatorFactory demonstrates how it is instantiated and configured.

ValidatorFactory Structure


Sources: src/ValidatorFactory.php13-29

Factory Initialization

The ValidatorFactory is a factory for the Factory class itself. It is invoked by the DI container and performs the following steps:

  1. Retrieve Translator - Resolves the Translator implementation from the container (src/ValidatorFactory.php16)
  2. Create Factory Instance - Instantiates a new Factory with translator and container (src/ValidatorFactory.php15-18)
  3. Configure Presence Verifier - If database integration is available, sets the presence verifier for database validation rules (src/ValidatorFactory.php23-26)

Database Integration Check

The factory conditionally configures database validation support:


This allows the exists and unique validation rules to function only when database dependencies are available.

Sources: src/ValidatorFactory.php23-26


Dependency Injection Integration

In Hyperf applications, validators are typically created through dependency injection. The integration follows this pattern:

Service Registration Flow


Sources: src/ValidatorFactory.php13-29

Typical Usage Pattern

Application code typically receives the Factory instance through constructor injection:



Validator Dependencies and Configuration

Core Dependencies

The validator system requires the following core dependencies to function:

DependencyInterface/ClassPurposeRequired
TranslatorHypervel\Translation\Contracts\TranslatorMessage translation and formattingYes
ContainerPsr\Container\ContainerInterfaceDependency resolution for extensionsYes (via Factory)
Presence VerifierPresenceVerifierInterfaceDatabase existence checksNo

Optional Dependencies

The presence verifier is optional and only needed for database validation rules:


Sources: src/Validator.php38-43 src/ValidatorFactory.php23-26

Setting Dependencies After Construction

The Validator class provides methods to inject dependencies after instantiation:

MethodParameter TypePurpose
setPresenceVerifier()PresenceVerifierInterfaceEnable database validation rules
setTranslator()TranslatorReplace translation service
setContainer()ContainerInterfaceSet container for extension resolution

These methods are located at:

Sources: src/Validator.php1313-1380


Data Preparation

The constructor performs automatic data preparation to handle special characters in array keys. This process is critical for supporting nested validation rules.

Key Transformation

The parseData() method recursively processes input data:

  1. Dot Replacement - Replaces literal dots (.) with __dot__[hash]
  2. Asterisk Replacement - Replaces literal asterisks (*) with __asterisk__[hash]
  3. Recursive Processing - Applies transformations to nested arrays

This transformation prevents conflicts between literal special characters in keys and the special meaning of these characters in validation rules (where . denotes nesting and * denotes wildcards).

Example Transformation


The transformation is reversed when retrieving validated data via the validated() method using replacePlaceholders() (src/Validator.php548).

Sources: src/Validator.php310-330 src/Validator.php335-346


Rule Initialization

The constructor delegates rule processing to the setRules() method, which performs several operations:

Rule Processing Flow


Sources: src/Validator.php304 src/Validator.php1050-1064 src/Validator.php1069-1085

Wildcard Expansion

The ValidationRuleParser automatically expands wildcard rules to match actual data structure:


The expansion result is stored in the implicitAttributes property (src/Validator.php1080-1084).

Sources: src/Validator.php1074-1079


Code Entity Reference

Primary Classes and Methods

The following table maps the validator creation process to specific code entities:

EntityLocationResponsibility
Validator::__construct()src/Validator.php284-305Initialize validator instance with dependencies
Validator::parseData()src/Validator.php310-330Transform data keys to escape special characters
Validator::setRules()src/Validator.php1050-1064Initialize and parse validation rules
Validator::addRules()src/Validator.php1069-1085Merge and expand rules using parser
ValidatorFactory::__invoke()src/ValidatorFactory.php13-29Create and configure Factory instance
Validator::setPresenceVerifier()src/Validator.php1313-1316Inject database presence verifier
Validator::setContainer()src/Validator.php1377-1380Inject DI container

Key Properties

Properties initialized during construction:

PropertyTypeSet AtPurpose
$translatorTranslatorsrc/Validator.php289Message translation service
$dataarraysrc/Validator.php301Parsed validation data
$initialRulesarraysrc/Validator.php299Original rule definitions
$rulesarraysrc/Validator.php304Expanded and parsed rules
$customMessagesarraysrc/Validator.php300Custom error messages
$customAttributesarraysrc/Validator.php302Custom attribute display names
$containerContainerInterface|nullsrc/Validator.php38DI container (set later)
$presenceVerifierPresenceVerifierInterface|nullsrc/Validator.php43Database verifier (set later)

Sources: src/Validator.php35-103 src/Validator.php284-305


Summary

Validator creation in the Hypervel Validation package follows a layered architecture:

  1. Foundation Layer - The Validator constructor handles data parsing and rule initialization
  2. Factory Layer - The ValidatorFactory creates Factory instances with proper dependency configuration
  3. Integration Layer - Hyperf's DI container manages factory registration and resolution

The recommended approach is to use the Factory through dependency injection, allowing the framework to handle dependency resolution and configuration while keeping application code clean and testable.

Sources: src/Validator.php284-305 src/ValidatorFactory.php13-29