VOOZH about

URL: https://deepwiki.com/hypervel/validation/8.1-dependency-injection-integration

⇱ Dependency Injection Integration | hypervel/validation | DeepWiki


Loading...
Menu

Dependency Injection Integration

Purpose and Scope

This document explains how the hypervel/validation package integrates with Hyperf's PSR-11 dependency injection container. It covers the service registration mechanism through ConfigProvider, the invokable factory pattern used for validator instantiation, dependency resolution strategies, and automatic validation via the ValidatesWhenResolved contract.

For information about creating validators using the factory, see Creating Validators. For details on configuring custom extensions, see Extensions and Customization.

Container Registration

The package uses Hyperf's automatic service discovery mechanism through ConfigProvider to register service bindings with the DI container. When the package is installed, Hyperf automatically detects and loads the configuration.

ConfigProvider Service Bindings

The src/ConfigProvider.php1-23 class defines three primary service bindings:

Abstract InterfaceConcrete ImplementationPurpose
FactoryContract::classValidatorFactory::classMain factory for creating validators
DatabasePresenceVerifierInterface::classPresenceVerifierFactory::classDatabase existence verification
UncompromisedVerifier::classUncompromisedVerifierFactory::classPassword breach checking

Service Registration Flow


Sources: src/ConfigProvider.php1-23 composer.json40-43

Registration Mechanism

The composer.json40-43 file specifies the ConfigProvider in the extra.hyperf.config section:


When Hyperf's framework boots, it:

  1. Reads the hyperf.config entry from all installed packages
  2. Invokes each ConfigProvider
  3. Merges the returned configuration arrays
  4. Registers the service bindings in the dependency injection container

Sources: composer.json40-43

ValidatorFactory: Invokable Factory Pattern

The ValidatorFactory class implements PHP's __invoke() magic method, making it an invokable factory. This pattern allows the class to be used as both a container binding and a callable factory.

Factory Instantiation Flow


Sources: src/ValidatorFactory.php1-31

Implementation Details

The src/ValidatorFactory.php13-29 method performs the following steps:

  1. Required Dependency Resolution: Retrieves Translator from the container (line 16)
  2. Factory Instantiation: Creates a new Factory instance with the translator and container (lines 15-18)
  3. Conditional Dependency Resolution: Checks for database availability (line 23)
  4. Presence Verifier Injection: If database components exist, injects DatabasePresenceVerifierInterface (lines 24-25)
  5. Factory Return: Returns the fully configured Factory instance (line 28)

The conditional dependency check at src/ValidatorFactory.php23 ensures graceful degradation when database components are not installed:


Sources: src/ValidatorFactory.php1-31

Dependency Resolution Strategy

The validation package follows a layered dependency resolution strategy that distinguishes between required and optional dependencies.

Dependency Hierarchy


Sources: src/ValidatorFactory.php1-31 composer.json28-36

Required Dependencies

The following dependencies are always required and must be present in the container:

DependencyPackagePurpose
Translatorhypervel/translationMessage localization and translation
ContainerInterfacePSR-11Dependency resolution and service location

These are declared in composer.json34-35:


Sources: composer.json28-36 src/ValidatorFactory.php16-17

Optional Dependencies

Optional dependencies are resolved conditionally based on availability:

DependencyPackageConditionPurpose
ConnectionResolverInterfacehyperf/databaseSuggestedDatabase connection management
DatabasePresenceVerifierInterfacePackage-providedRequires databaseUnique/exists validation rules
UncompromisedVerifierPackage-providedOptionalPassword breach checking

The database dependency is noted as a suggestion in composer.json49:


Sources: composer.json48-51 src/ValidatorFactory.php23-26 src/ConfigProvider.php17-18

ValidatesWhenResolved Contract

The ValidatesWhenResolved contract provides a mechanism for automatic validation when an object is resolved from the DI container. This is particularly useful for form request objects that should be validated immediately upon instantiation.

Contract Definition

The src/Contracts/ValidatesWhenResolved.php1-14 interface defines a single method:


Automatic Validation Flow


Sources: src/Contracts/ValidatesWhenResolved.php1-14

Usage Pattern

Classes implementing ValidatesWhenResolved are typically used in request handling scenarios:

  1. Implementation: A form request class implements the ValidatesWhenResolved interface
  2. Container Resolution: When the container resolves the class, it detects the interface
  3. Automatic Invocation: The container's middleware automatically calls validateResolved()
  4. Validation Execution: The method performs validation using the validator factory
  5. Error Handling: If validation fails, a ValidationException is thrown

This pattern enables declarative validation without explicit validation calls in controllers.

Sources: src/Contracts/ValidatesWhenResolved.php1-14

Service Binding Reference

The following table provides a complete reference of all service bindings registered by the validation package:

Primary Service Bindings

AbstractConcreteLifecycleDependencies
Hypervel\Validation\Contracts\FactoryValidatorFactory (invokable)SingletonTranslator, ContainerInterface
DatabasePresenceVerifierInterfacePresenceVerifierFactory (invokable)SingletonConnectionResolverInterface
UncompromisedVerifierUncompromisedVerifierFactory (invokable)SingletonHTTP client dependencies

Dependency Resolution Graph


Sources: src/ConfigProvider.php14-20 src/ValidatorFactory.php1-31

Resolution Behavior

The container resolves these bindings with the following behavior:

  1. Invokable Pattern: All factory bindings use the invokable pattern (__invoke() method)
  2. Lazy Resolution: Dependencies are only resolved when the factory is first requested
  3. Conditional Injection: Optional dependencies are checked before injection
  4. Singleton Lifecycle: Most services are singletons, created once and reused
  5. Dependency Graph: Container automatically resolves transitive dependencies

Sources: src/ConfigProvider.php1-23 src/ValidatorFactory.php1-31

Integration with PSR-11 Container

The validation package follows PSR-11 container standards for maximum interoperability with Hyperf and other PHP frameworks.

Container Interface Usage

The package uses the ContainerInterface from PSR-11 for all container operations:

MethodUsage LocationPurpose
get(string $id)ValidatorFactory.php16-24Resolve required and optional dependencies
has(string $id)ValidatorFactory.php23Check for optional dependency availability

Container Method Semantics


Sources: src/ValidatorFactory.php23-26

Best Practices

The validation package demonstrates several PSR-11 best practices:

  1. Check Before Resolve: Always use has() before get() for optional dependencies (ValidatorFactory.php23)
  2. Constructor Injection: Accept ContainerInterface in constructor rather than storing globally
  3. Service Locator Pattern: Use container for dynamic dependency resolution in factory
  4. Graceful Degradation: Provide reduced functionality when optional dependencies unavailable
  5. Type Hints: Always type-hint container as ContainerInterface for framework independence

Sources: src/ValidatorFactory.php1-31