VOOZH about

URL: https://deepwiki.com/hypervel/components/9-data-structures-and-patterns

⇱ Data Structures and Patterns | hypervel/components | DeepWiki


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

Data Structures and Patterns

This document describes the core reusable data structures and design patterns used throughout the Hypervel framework. These patterns provide consistent abstractions for common programming challenges, enabling extensibility, maintainability, and type safety across the codebase.

The framework employs two primary structural patterns:

  • DataObject Pattern: Immutable, type-safe structured data objects with automatic casting and serialization
  • Manager Pattern: Abstract driver resolution with lazy initialization and custom creator registration

For specific implementation details of individual patterns, see DataObject Pattern and Manager Pattern for Driver Resolution. For monitoring and debugging patterns using Aspect-Oriented Programming, see Aspect-Oriented Programming.


Pattern Overview

The following diagram shows how these patterns are distributed across the framework's major systems:

Diagram: Pattern Usage Across Framework Components


Sources: src/support/src/DataObject.php1-588 src/support/src/Manager.php1-158 src/core/src/Database/Eloquent/Casts/AsDataObject.php1-70 src/telescope/src/Aspects/GuzzleHttpClientAspect.php1-29


DataObject Pattern

The DataObject pattern provides immutable, type-safe data transfer objects with automatic type casting, property mapping, and nested object resolution. It is designed for structured data that flows through the application without business logic.

Key Characteristics

FeatureDescription
ImmutabilityArray access is read-only; throws LogicException on mutation attempts
Type CastingAutomatic conversion of scalar types (int, float, string, bool, array)
Property MappingBidirectional conversion between camelCase properties and snake_case data keys
Nested ResolutionRecursive instantiation of nested DataObjects, DateTimes, and Enums
SerializationImplements JsonSerializable and provides toArray() for API responses
CachingReflection metadata cached statically; array representation cached per instance

Architecture

Diagram: DataObject Class Structure


Sources: src/support/src/DataObject.php22-588 src/core/src/Database/Eloquent/Casts/AsDataObject.php11-70

DataObject Instantiation Flow

Diagram: DataObject.make() Execution Sequence


Sources: src/support/src/DataObject.php62-93 src/support/src/DataObject.php193-346 src/support/src/DataObject.php411-432

Common Use Cases

The following table shows typical DataObject usage patterns observed in the codebase:

Use CaseImplementationKey Methods
API Request DTOsStructured input from HTTP requestsmake($request->all()), toArray()
Eloquent Model AttributesStore complex objects as JSON in databaseAsDataObject::castUsing(AddressDataObject::class)
Queue Job PayloadsSerialize job parameters for queue storagejsonSerialize(), make($data, true)
Nested Object TreesHierarchical data structuresautoResolve = true, resolveDependenciesMap()
DateTime HandlingAutomatic Carbon instance creationasDateTime(), custom serializers

Integration with Eloquent

The AsDataObject cast enables seamless storage of DataObject instances in Eloquent model attributes:


When retrieving the attribute, the JSON string is automatically deserialized to a DataObject instance using make($data, true). When saving, the object is serialized to JSON via json_encode($value).

Sources: src/core/src/Database/Eloquent/Casts/AsDataObject.php31-60 tests/Support/DataObjectTest.php309-332

For detailed information about DataObject features including nested resolution, custom type handlers, and property mapping configuration, see DataObject Pattern.


Manager Pattern

The Manager pattern provides a consistent interface for resolving and caching driver instances across service layers. It implements lazy initialization, custom driver registration, and method proxying to the default driver.

Key Characteristics

FeatureDescription
Lazy InitializationDrivers created only when first requested via driver()
Convention-Based ResolutionMethods named create{Driver}Driver() using StudlyCase
Custom CreatorsRegister closures via extend() for custom driver implementations
Instance CachingCreated drivers stored in $drivers array for reuse
Method Proxying__call() delegates to default driver for convenience
Container IntegrationResolves dependencies via ContainerInterface

Architecture

Diagram: Manager Pattern Class Structure


Sources: src/support/src/Manager.php13-158

Driver Resolution Flow

Diagram: Manager Driver Resolution Sequence


Sources: src/support/src/Manager.php49-84 src/support/src/Manager.php89-92

Manager Pattern Implementations

The framework uses the Manager pattern extensively for service layer abstraction:

Manager ClassConfiguration KeyAvailable Drivers
CacheManagercache.defaultredis, file, array, swoole, stack, database
BroadcastManagerbroadcasting.defaultpusher, ably, redis, log, null
QueueManagerqueue.defaultredis, database, sync
FilesystemManagerfilesystems.defaultlocal, s3, ftp, sftp
MailManagermail.defaultsmtp, sendmail, mailgun, ses, postmark

Method Proxying Example

The __call() magic method enables convenient access to the default driver:


This pattern eliminates the need to repeatedly call driver() when working with the default driver, while still allowing explicit driver selection when needed.

Sources: src/support/src/Manager.php153-156

Custom Driver Registration

Applications can register custom drivers at runtime using the extend() method:


The custom creator closure receives the ContainerInterface instance, enabling full dependency resolution for complex driver implementations.

Sources: src/support/src/Manager.php99-104

For detailed information about Manager pattern usage including driver lifecycle, configuration patterns, and extension examples, see Manager Pattern for Driver Resolution.


Supporting Patterns

The framework employs several additional patterns that complement the core structural patterns:

Factory Pattern

Used throughout the codebase for object creation with complex initialization:

  • DataObject::make(): Factory method for creating instances from arrays src/support/src/DataObject.php62-93
  • DispatcherFactory: Creates FastRoute dispatcher instances with route registration [Referenced in architecture diagrams]
  • HTTP Client Factory: Creates configured HTTP client instances with middleware [Referenced in architecture diagrams]

Strategy Pattern

Implemented via driver-based managers where each driver provides an alternate algorithm:

  • Cache eviction strategies (LRU, LFU, TTL) in SwooleStore
  • Broadcasting protocols (Pusher, Ably, Redis) in BroadcastManager
  • Queue backends (Redis, Database, Sync) in QueueManager

Aspect-Oriented Programming (AOP)

The framework uses Hyperf's AOP system for cross-cutting concerns, particularly in monitoring:

Diagram: AOP Integration with GuzzleHttpClientAspect


Sources: src/telescope/src/Aspects/GuzzleHttpClientAspect.php13-28 src/telescope/src/Watchers/HttpClientWatcher.php35-83

The aspect intercepts all calls to GuzzleHttp\Client::transfer(), wraps the execution with monitoring logic, and transparently records the request/response data without modifying application code.

For more information about AOP usage in monitoring, see Aspect-Oriented Programming.

Repository Pattern

While not explicitly documented, the Repository pattern appears in cache implementations:

  • Repository class wraps cache stores and provides a consistent interface
  • Each cache driver (Redis, File, Array, etc.) implements the store contract
  • The CacheManager resolves store instances and wraps them in Repository

Service Provider Pattern

Used for bootstrapping and service registration, detailed in Service Providers and Bootstrapping.


Pattern Selection Guidelines

The following decision matrix helps determine which pattern to apply:

RequirementRecommended PatternRationale
Immutable structured dataDataObjectType safety, serialization, property mapping
Multiple implementations of same interfaceManagerDriver resolution, lazy loading, extensibility
Cross-cutting concernsAOP AspectSeparation of concerns, transparent interception
Complex object creationFactoryEncapsulates initialization logic
Algorithm selection at runtimeStrategy (via Manager)Swappable implementations via configuration
Data access abstractionRepositoryConsistent interface, testability

Performance Considerations

Both primary patterns employ aggressive caching strategies:

DataObject Caching:

  • Reflection metadata: Static class-level cache ($reflectionParametersCache, $propertyMapCache, $dependenciesMapCache)
  • Array representation: Instance-level cache ($arrayCache)
  • Cache cleared via refresh() method after mutations

Manager Caching:

  • Driver instances: Cached in $drivers array after first creation
  • Configuration: Resolved once from ConfigInterface during manager construction
  • Cache cleared via forgetDrivers() for testing or runtime reconfiguration

Sources: src/support/src/DataObject.php24-47 src/support/src/Manager.php21-28


Testing Patterns

The framework provides testing utilities for both patterns:

DataObject Testing

Test classes demonstrate proper usage including:

Manager Testing

Manager implementations should test:

  • Default driver resolution
  • Custom driver registration via extend()
  • Driver instance caching
  • Method proxying via __call()
  • Invalid driver exception handling

For HTTP client testing patterns using fake drivers, see HTTP Testing and Request Mocking.


Summary

The DataObject and Manager patterns form the structural foundation of the Hypervel framework:

  • DataObject provides type-safe, immutable data structures with automatic casting and nested resolution, suitable for DTOs, API responses, and Eloquent attribute storage
  • Manager provides consistent driver resolution with lazy initialization and extensibility, enabling the framework's multi-driver architecture for caches, queues, broadcasting, and more

These patterns, combined with supporting patterns like Factory, Strategy, and AOP, create a cohesive architecture that balances performance, extensibility, and developer experience.

Sources: src/support/src/DataObject.php1-588 src/support/src/Manager.php1-158 src/core/src/Database/Eloquent/Casts/AsDataObject.php1-70 src/telescope/src/Aspects/GuzzleHttpClientAspect.php1-29 tests/Support/DataObjectTest.php1-490