VOOZH about

URL: https://deepwiki.com/hypervel/config/5.3-type-safe-configuration-access

⇱ Type-Safe Configuration Access | hypervel/config | DeepWiki


Loading...
Menu

Type-Safe Configuration Access

Purpose and Scope

This document explains the type-safe configuration getter methods provided by the Repository class. These methods (string(), integer(), float(), boolean(), and array()) offer runtime type validation, ensuring that retrieved configuration values match expected types or throwing exceptions when type mismatches occur. This mechanism helps catch configuration errors early and provides stronger type guarantees than the generic get() method.

For information about the Repository class and its other methods, see Repository Class. For general configuration retrieval patterns using the config() helper, see Configuration Function.

Type-Safe Method Overview

The Repository class provides five type-safe getter methods that validate configuration values at runtime. Each method retrieves a configuration value, validates its type, and either returns the typed value or throws an InvalidArgumentException.

Available Type-Safe Methods

MethodReturn TypeValidates TypeException on Mismatch
string()stringis_string()Yes
integer()intis_int()Yes
float()floatis_float()Yes
boolean()boolis_bool()Yes
array()arrayis_array()Yes

All methods accept the same parameters:

  • string $key - The configuration key (supports dot notation)
  • mixed $default = null - Default value if key does not exist (can be a Closure)

Sources: src/Repository.php68-157

Method Implementation Pattern

All type-safe methods follow a consistent three-step pattern implemented in the Repository class:


Diagram: Type-Safe Method Execution Flow

Each method:

  1. Calls the underlying get() method to retrieve the value from the configuration store
  2. Performs type validation using PHP's native type-checking functions
  3. Returns the value if valid, or throws an InvalidArgumentException with a message indicating the expected type, the key, and the actual type received

Sources: src/Repository.php68-157

Detailed Method Specifications

string() Method

The string() method retrieves a configuration value and validates it is a string.

Method Signature:


Implementation Location: src/Repository.php73-84

Behavior:

  • Retrieves value using get($key, $default)
  • Validates using is_string($value)
  • Throws exception if value is not a string
  • Exception format: "Configuration value for key [%s] must be a string, %s given."

Sources: src/Repository.php73-84

integer() Method

The integer() method retrieves a configuration value and validates it is an integer.

Method Signature:


Implementation Location: src/Repository.php91-102

Behavior:

  • Retrieves value using get($key, $default)
  • Validates using is_int($value)
  • Throws exception if value is not an integer
  • Exception format: "Configuration value for key [%s] must be an integer, %s given."

Note: This method does NOT accept numeric strings. The value must be a true PHP integer type.

Sources: src/Repository.php91-102

float() Method

The float() method retrieves a configuration value and validates it is a float.

Method Signature:


Implementation Location: src/Repository.php109-120

Behavior:

  • Retrieves value using get($key, $default)
  • Validates using is_float($value)
  • Throws exception if value is not a float
  • Exception format: "Configuration value for key [%s] must be a float, %s given."

Note: Integers are NOT automatically converted to floats. The value must be a true PHP float type.

Sources: src/Repository.php109-120

boolean() Method

The boolean() method retrieves a configuration value and validates it is a boolean.

Method Signature:


Implementation Location: src/Repository.php127-138

Behavior:

  • Retrieves value using get($key, $default)
  • Validates using is_bool($value)
  • Throws exception if value is not a boolean
  • Exception format: "Configuration value for key [%s] must be a boolean, %s given."

Note: Truthy/falsy values (like 1, 0, "true", "false") are NOT accepted. Only PHP boolean true or false values are valid.

Sources: src/Repository.php127-138

array() Method

The array() method retrieves a configuration value and validates it is an array.

Method Signature:


Implementation Location: src/Repository.php146-157

Behavior:

  • Retrieves value using get($key, $default)
  • Validates using is_array($value)
  • Throws exception if value is not an array
  • Exception format: "Configuration value for key [%s] must be an array, %s given."

Sources: src/Repository.php146-157

Type Validation and Error Handling

Validation Mechanism

The type validation process occurs immediately after value retrieval and before the value is returned to the caller:


Diagram: Type Validation Sequence

The validation uses PHP's native type-checking functions (is_string(), is_int(), is_float(), is_bool(), is_array()) which operate on the value's actual runtime type, not loose type coercion.

Sources: src/Repository.php68-157

Exception Details

When type validation fails, all methods throw InvalidArgumentException with a consistent message format that includes:

  1. The configuration key that was accessed
  2. The expected type
  3. The actual type received (using gettype())

Exception Construction: src/Repository.php78-80 src/Repository.php96-98 src/Repository.php114-116 src/Repository.php132-134 src/Repository.php151-153

Example exception message:

Configuration value for key [database.port] must be an integer, string given.

The exception is thrown from within the type-safe method, so the stack trace will point to the call site, making debugging straightforward.

Sources: src/Repository.php78-80 src/Repository.php96-98 src/Repository.php114-116 src/Repository.php132-134 src/Repository.php151-153

Comparison with get() Method


Diagram: Comparison of get() vs Type-Safe Methods

Aspectget() MethodType-Safe Methods
Return TypemixedSpecific type (string, int, float, bool, array)
Type CheckingNoneStrict runtime validation
Error on Type MismatchNo - returns whatever type existsYes - throws InvalidArgumentException
PerformanceMinimal overheadAdditional type check per call
Use CaseGeneral access, dynamic typesCritical configuration where type matters

Key Differences:

  1. Type Safety: get() returns any type without validation. Type-safe methods enforce specific types.

  2. Error Detection: get() silently returns mistyped values, potentially causing errors downstream. Type-safe methods fail fast at the access point.

  3. IDE Support: Type-safe methods provide better IDE autocomplete and static analysis support due to explicit return types.

  4. Default Value Handling: Both support default values, but type-safe methods validate the retrieved value (whether from config or default).

Sources: src/Repository.php41-48 src/Repository.php68-157

Usage Patterns and Best Practices

When to Use Type-Safe Methods

Recommended Use Cases:

ScenarioMethodRationale
Application name, API keys, service URLsstring()Critical identifiers must be strings
Port numbers, timeouts, retry countsinteger()Numeric parameters that drive behavior
Threshold values, percentagesfloat()Precise numeric calculations
Feature flags, debug mode, enable/disable settingsboolean()Binary configuration decisions
Service credentials, middleware lists, routesarray()Structured configuration data

When to Use Generic get() Instead:

  • Configuration values with intentionally mixed types
  • Optional configuration that might not exist (using null defaults)
  • Performance-critical paths where type validation overhead matters
  • Debugging/inspection code that handles arbitrary configuration

Sources: src/Repository.php68-157

Access Pattern Examples


Diagram: Type-Safe Access Patterns in Application Code

Usage Pattern 1 - Direct Type-Safe Access:


Usage Pattern 2 - Dependency Injection:


Usage Pattern 3 - With Default Values:


Usage Pattern 4 - With Closure Defaults:


Sources: src/Repository.php68-157

Error Handling Strategy

Strategy 1 - Fail Fast (Recommended): Let exceptions propagate to expose configuration problems early in the application lifecycle:


Strategy 2 - Graceful Degradation: Catch exceptions for non-critical configuration and provide fallbacks:


Strategy 3 - Validation During Configuration Loading: Validate critical configuration immediately after application bootstrap to fail before handling requests.

Sources: src/Repository.php68-157

Implementation Architecture


Diagram: Type-Safe Method Implementation Architecture

Key Implementation Details:

  1. Storage: All configuration data resides in the protected $items array src/Repository.php26

  2. Retrieval: Type-safe methods delegate to get() which uses Hyperf\Collection\Arr::get() for nested key access src/Repository.php47

  3. Validation: Each method uses PHP's native type-checking function (is_string(), etc.) src/Repository.php77 src/Repository.php95 src/Repository.php113 src/Repository.php131 src/Repository.php150

  4. Error Reporting: gettype() provides runtime type information for exception messages src/Repository.php79 src/Repository.php97 src/Repository.php115 src/Repository.php133 src/Repository.php152

  5. Exception Handling: InvalidArgumentException is thrown with descriptive message on type mismatch src/Repository.php78-80 src/Repository.php96-98 src/Repository.php114-116 src/Repository.php132-134 src/Repository.php151-153

Sources: src/Repository.php68-157

Type Coercion and Strict Validation

The type-safe methods perform strict type validation without any type coercion. This is an important characteristic:

Value in ConfigType Checkstring()integer()float()boolean()array()
"123"string✓ Pass✗ Fail✗ Fail✗ Fail✗ Fail
123integer✗ Fail✓ Pass✗ Fail✗ Fail✗ Fail
123.45float✗ Fail✗ Fail✓ Pass✗ Fail✗ Fail
trueboolean✗ Fail✗ Fail✗ Fail✓ Pass✗ Fail
1 (integer)integer✗ Fail✓ Pass✗ Fail✗ Fail✗ Fail
[]array✗ Fail✗ Fail✗ Fail✗ Fail✓ Pass

No Automatic Conversion:

  • String "123" is NOT converted to integer 123
  • Integer 1 is NOT treated as boolean true
  • Integer 123 is NOT converted to float 123.0
  • String "true" is NOT converted to boolean true

This strict validation ensures configuration errors are caught immediately rather than silently producing unexpected behavior through type coercion.

Sources: src/Repository.php68-157