VOOZH about

URL: https://deepwiki.com/hypervel/validation/5-factory-and-configuration

⇱ Factory and Configuration | hypervel/validation | DeepWiki


Loading...
Menu

Factory and Configuration

Purpose and Scope

This document explains the factory pattern and configuration architecture used to create and configure Validator instances. It covers the dependency injection system, service registration, and how the factory manages custom extensions and configuration options.

For practical examples of creating validators, see Creating Validators. For details on registering custom extensions and replacers, see Extensions and Customization.


Factory Pattern Overview

The validation package uses a two-tier factory pattern to separate concerns between service instantiation and validator configuration:


Factory Hierarchy:

ClassTypeResponsibility
Contracts\FactoryInterfaceDefines factory contract with make(), extend(), extendImplicit(), replacer() methods
ValidatorFactoryInvokable FactoryCreates Factory instances, injects dependencies from container
FactoryConcrete FactoryCreates Validator instances, manages configuration, applies extensions

Sources: src/Contracts/Factory.php1-31 src/ValidatorFactory.php1-31 src/Factory.php1-260


Dependency Injection Architecture

The package integrates with PSR-11 dependency injection containers via ConfigProvider, which registers factory contracts and their implementations:


The ConfigProvider::__invoke() method src/ConfigProvider.php12-21 returns a configuration array mapping abstract contracts to concrete factory classes:


Dependency Resolution:

DependencyRequiredPurposeInjection Point
TranslatorYesMessage localizationValidatorFactory::__invoke():16
ContainerInterfaceYesResolve custom extensionsValidatorFactory::__invoke():17
DatabasePresenceVerifierInterfaceNoDatabase validation (unique, exists rules)ValidatorFactory::__invoke():23-26
ConnectionResolverInterfaceNoPrerequisite for database verifierValidatorFactory::__invoke():23

Sources: src/ConfigProvider.php1-23 src/ValidatorFactory.php13-29


ValidatorFactory: Service Instantiation

The ValidatorFactory class is an invokable factory that creates Factory instances with all required dependencies injected:


The factory performs conditional dependency injection at src/ValidatorFactory.php23-26:


This design allows the validation package to function without database components, gracefully degrading when optional dependencies are unavailable.

Sources: src/ValidatorFactory.php1-31


Factory: Configuration Management

The Factory class manages validation configuration and creates Validator instances. It stores custom extensions, message replacers, and configuration options:


Configuration Properties

PropertyTypeDefaultPurpose
$translatorTranslator(required)Provides message localization
$containerContainerInterface(required)Resolves class-based extensions
$verifierPresenceVerifierInterfacenullChecks database presence for unique/exists
$extensionsarray<string, Closure|string>[]Standard custom validation rules
$implicitExtensionsarray<string, Closure|string>[]Custom rules that run even when attribute missing
$dependentExtensionsarray<string, Closure|string>[]Custom rules that depend on other fields
$replacersarray<string, Closure|string>[]Custom message placeholder replacers
$fallbackMessagesarray<string, string>[]Default messages for custom rules
$excludeUnvalidatedArrayKeysbooltrueWhether to exclude unvalidated array keys from validated data
$resolverClosure|nullnullCustom validator instantiation logic

Sources: src/Factory.php14-64


Validator Instantiation Flow

When Factory::make() is called, it follows this instantiation sequence:


Instantiation Steps

  1. Resolve Validator Instance src/Factory.php123-130

    • If custom $resolver exists, call it with validator parameters
    • Otherwise, instantiate new Validator(...) with default constructor
  2. Inject Dependencies src/Factory.php92-101

    • Set presence verifier if available (for database rules)
    • Set container if available (for class-based extensions)
    • Copy excludeUnvalidatedArrayKeys setting
  3. Apply Extensions src/Factory.php135-149

    • Add standard extensions via addExtensions()
    • Add implicit extensions via addImplicitExtensions()
    • Add dependent extensions via addDependentExtensions()
    • Add message replacers via addReplacers()
    • Set fallback messages via setFallbackMessages()

Sources: src/Factory.php80-149


Factory Contract Methods

The Contracts\Factory interface defines four primary methods:

make()


Creates a new Validator instance with specified data and rules. The concrete implementation also handles dependency injection and extension registration. src/Contracts/Factory.php14

extend()


Registers a custom validation rule that runs on present attributes. If $extension is a string, it must be a container-resolvable class name. src/Contracts/Factory.php19 src/Factory.php154-161

extendImplicit()


Registers a custom validation rule that runs even when the attribute is missing from the data array. Similar to built-in rules like required and accepted. src/Contracts/Factory.php24 src/Factory.php166-173

replacer()


Registers a custom message placeholder replacer for a validation rule. Replacers receive the message, attribute, rule, and parameters, and return the modified message. src/Contracts/Factory.php29 src/Factory.php190-193

Sources: src/Contracts/Factory.php1-31 src/Factory.php154-193


Custom Validator Resolver

The Factory supports complete customization of validator instantiation via the resolver() method:


The resolver closure receives the same parameters as the Validator constructor:


This allows applications to:

  • Extend the Validator class with custom behavior
  • Inject additional dependencies
  • Modify validator construction logic

The resolver is invoked at src/Factory.php129 during resolve().

Sources: src/Factory.php123-130 src/Factory.php214-217


Configuration Methods

Array Key Validation Control

The Factory provides methods to control whether unvalidated array keys are included in validated data:


When set to exclude (default), only keys with explicit validation rules are included in the validated data, even if their parent array was validated. This setting is copied to each Validator instance at src/Factory.php103

Sources: src/Factory.php198-209

Dependency Access

The Factory provides getters and setters for its core dependencies:

MethodPurpose
getTranslator()Returns the Translator instance src/Factory.php222-225
getPresenceVerifier()Returns the PresenceVerifierInterface instance src/Factory.php230-233
setPresenceVerifier()Sets the presence verifier src/Factory.php238-241
getContainer()Returns the ContainerInterface instance src/Factory.php246-249
setContainer()Sets the container and returns $this for chaining src/Factory.php254-259

Sources: src/Factory.php222-259


Extension Storage Architecture

Custom extensions are stored in separate arrays based on their execution behavior:


Extension Types:

  • Standard Extensions ($extensions): Run only when attribute exists in data
  • Implicit Extensions ($implicitExtensions): Run even when attribute is missing
  • Dependent Extensions ($dependentExtensions): Run when dependent field values meet conditions
  • Replacers ($replacers): Custom message placeholder replacement logic
  • Fallback Messages ($fallbackMessages): Default error messages for custom rules

When registering an extension with an optional $message parameter, the message is stored in $fallbackMessages using the snake_case version of the rule name src/Factory.php159 src/Factory.php171 src/Factory.php183

Sources: src/Factory.php21-53 src/Factory.php135-149 src/Factory.php154-185


Convenience Validation Method

The Factory provides a convenience method validate() that combines validator creation and validation execution:


This method creates a validator via make() and immediately calls validate() on it, returning the validated data or throwing ValidationException on failure. Implemented at src/Factory.php115-118

Sources: src/Factory.php115-118