VOOZH about

URL: https://deepwiki.com/hypervel/components/9.1-dataobject-pattern

⇱ DataObject Pattern | hypervel/components | DeepWiki


Loading...
Last indexed: 7 March 2026 (96fbab)
Menu

DataObject Pattern

Purpose and Scope

The DataObject pattern provides an immutable, type-safe data transfer object implementation with automatic type casting, property mapping, nested object resolution, and JSON serialization. DataObjects serve as structured containers for data throughout the Hypervel framework, particularly useful for API responses, configuration objects, and structured database column data.

This document covers the DataObject abstract class and its integration with Eloquent models. For information about the Manager pattern used for driver resolution, see Manager Pattern for Driver Resolution.

Sources: src/support/src/DataObject.php1-589


Overview and Core Features

The DataObject abstract class is located at src/support/src/DataObject.php22 and provides:

  • Factory pattern creation via make() and from() methods
  • Automatic type casting between primitive types (int, float, string, bool, array)
  • Property name mapping between snake_case keys and camelCase properties
  • Nested object resolution for DataObject, DateTime, and Enum dependencies
  • JSON serialization support via JsonSerializable interface
  • Read-only array access via ArrayAccess interface
  • Reflection caching for performance optimization

DataObjects are immutable via array access but allow direct property mutation followed by cache refresh.

Sources: src/support/src/DataObject.php22-93


Class Architecture


Sources: src/support/src/DataObject.php22-93 src/core/src/Database/Eloquent/Casts/AsDataObject.php1-69


Basic Usage and Creation

Factory Method Creation

DataObjects are created using the static make() or from() methods (aliases):


The factory method handles:

  1. Property mapping from snake_case array keys to camelCase constructor parameters
  2. Type casting of string values to correct types (when $autoCasting is enabled)
  3. Default value resolution from constructor parameter defaults
  4. Required parameter validation with meaningful exceptions

Sources: src/support/src/DataObject.php62-93 tests/Support/DataObjectTest.php25-47


Type Casting System

Automatic Type Conversion

When $autoCasting is enabled (default), the convertValueToType() method automatically casts values:

Target TypeConversion Behavior
intCast to integer via (int) $value
floatCast to float via (float) $value
stringCast to string via (string) $value
boolCast to boolean via (bool) $value
arrayWrap non-arrays in array: [$value]

Disabling Auto-Casting

Auto-casting can be disabled per-class or globally:


Sources: src/support/src/DataObject.php349-432 tests/Support/DataObjectTest.php147-164


Property Name Mapping

Default Mapping Strategy

By default, DataObject converts between snake_case array keys and camelCase property names:


Property Map Caching

Property maps are cached in static arrays to avoid repeated reflection:

  • $propertyMapCache: Maps snake_case keys to camelCase properties
  • $reversedPropertyMapCache: Maps camelCase properties to snake_case keys
  • $reflectionParametersCache: Caches constructor ReflectionParameter[]

Custom Mapping

Override the conversion methods for custom naming strategies:


Sources: src/support/src/DataObject.php376-489 tests/Support/DataObjectTest.php131-142


Nested Object Resolution

Auto-Resolve Mode

When autoResolve = true, DataObject automatically resolves nested dependencies:


Nested DataObject Example


Deep Nesting Support

The dependency resolver handles arbitrary nesting depth via recursive resolveDependenciesMap():


Sources: src/support/src/DataObject.php193-346 tests/Support/DataObjectTest.php309-363


DateTime and Carbon Support

DateTime Dependency Handling

DataObject provides special handling for DateTime-related types via customized dependencies:


asDateTime() Conversion Logic

The asDateTime() method src/support/src/DataObject.php139-180 handles multiple input formats:

  1. Already Carbon: Returns Carbon::instance($value)
  2. DateTimeInterface: Parses with timezone preservation
  3. Numeric: Treats as UNIX timestamp via Carbon::createFromTimestamp()
  4. Y-m-d format: Creates from standard date format
  5. Custom format: Uses $dateFormat static property
  6. Fallback: Uses Carbon::parse() for flexible parsing

DateTime Serialization

When serializing to array/JSON, DateTime objects are converted to ISO 8601 format:


Sources: src/support/src/DataObject.php109-180 src/support/src/DataObject.php125-134


Enum Support

Automatic Enum Resolution

When autoResolve = true, enum properties are automatically resolved using their from() method:


Enum Detection Logic

The dependency resolver detects enums via enum_exists() check and registers them with the from() handler src/support/src/DataObject.php292-298:


Sources: src/support/src/DataObject.php292-298 tests/Support/DataObjectTest.php485-489


Serialization and Array Access

toArray() Method

The toArray() method recursively converts the object to an array representation:


JSON Serialization

DataObject implements JsonSerializable by delegating to toArray():


ArrayAccess Interface

DataObject implements read-only array access:

MethodBehavior
offsetExists($offset)Checks if key exists in property map
offsetGet($offset)Returns value from toArray()
offsetSet($offset, $value)Throws LogicException (immutable)
offsetUnset($offset)Throws LogicException (immutable)

Sources: src/support/src/DataObject.php509-577 tests/Support/DataObjectTest.php169-217


Mutation and Cache Management

Direct Property Mutation

While array access is immutable, properties can be mutated directly:


update() Method

The update() method provides batch property updates with automatic cache refresh:


Cache Refresh

The refresh() method clears the $arrayCache to ensure toArray() reflects current values:


Sources: src/support/src/DataObject.php494-587 tests/Support/DataObjectTest.php52-115


Eloquent Integration

AsDataObject Cast

The AsDataObject cast src/core/src/Database/Eloquent/Casts/AsDataObject.php11-69 enables storing DataObject instances in database columns:


Cast Usage


Cast Implementation

The get() method decodes JSON and calls make() with autoResolve = true:


The set() method simply JSON encodes the value:


Sources: src/core/src/Database/Eloquent/Casts/AsDataObject.php11-69


Union Type Support

Union Type Dependency Resolution

DataObject supports union types in constructor parameters, extracting the relevant dependency type:


Union Type Handling Logic

The getDependencyFromUnionType() method src/support/src/DataObject.php219-232 extracts the first valid type:


Nullable Union Detection

The hasNullableUnionType() method checks if any type in the union allows null:


Sources: src/support/src/DataObject.php219-246 tests/Support/DataObjectTest.php368-383


Performance Optimization

Multi-Level Caching Strategy

DataObject employs several caching layers to minimize reflection overhead:

CacheKeyValuePurpose
$reflectionParametersCacheClass nameReflectionParameter[]Cache constructor parameters
$propertyMapCacheClass name[snake_key => camelProp]Cache property name mappings
$reversedPropertyMapCacheClass name[camelProp => snake_key]Cache reversed mappings
$dependenciesMapCacheClass nameDependency treeCache nested object structure
$arrayCacheInstance propertyArrayCache array representation

Cache Initialization Flow


Circular Dependency Prevention

The resolveDependenciesMap() method uses a $visited array to prevent infinite recursion:


Sources: src/support/src/DataObject.php24-57 src/support/src/DataObject.php254-313


Error Handling

Required Parameter Validation

DataObject throws RuntimeException when required parameters are missing:


Example Error


Cast Validation

The AsDataObject cast validates the class argument:


Sources: src/support/src/DataObject.php438-447 src/core/src/Database/Eloquent/Casts/AsDataObject.php13-23 tests/Support/DataObjectTest.php120-126


Integration Points

Framework Usage

DataObject is used throughout Hypervel for structured data:

  1. API Resources: Transform Eloquent models to structured JSON responses
  2. Configuration Objects: Type-safe configuration data structures
  3. Database Column Casting: Store complex objects in JSON columns via AsDataObject
  4. Queue Job Payloads: Serialize structured data for queue jobs
  5. Broadcasting Events: Structure event data for WebSocket broadcasts

Service Provider Integration

The VendorPublishCommand src/foundation/src/Console/Commands/VendorPublishCommand.php1-166 demonstrates DataObject usage for configuration structures, though not explicitly shown in the provided code.

Testing Infrastructure

DataObject includes comprehensive test coverage at tests/Support/DataObjectTest.php1-490 with test cases for:

  • Basic creation and type casting
  • Property mapping customization
  • Nested object resolution
  • Array access interface
  • JSON serialization
  • Union type support
  • Error conditions

Sources: tests/Support/DataObjectTest.php1-490 src/foundation/src/Console/Commands/VendorPublishCommand.php1-166


Best Practices

When to Use DataObject

Recommended Use Cases:

  • API request/response data structures
  • Configuration objects requiring validation
  • Complex database column values (via AsDataObject)
  • Immutable value objects in domain logic
  • Queue job payloads requiring structure

Not Recommended For:

  • Simple key-value pairs (use arrays)
  • Mutable state objects (use regular classes)
  • Performance-critical hot paths (avoid reflection overhead)

Defining DataObjects


Performance Considerations

  1. Enable caching: Static caches persist across requests in Swoole
  2. Use autoResolve sparingly: Only enable when nested resolution is needed
  3. Avoid deep nesting: Each nesting level adds reflection overhead
  4. Reuse instances: DataObjects are immutable, so they're safe to reuse

Sources: src/support/src/DataObject.php1-589 tests/Support/DataObjectTest.php1-490

Refresh this wiki

On this page