VOOZH about

URL: https://deepwiki.com/hypervel/api-client/4.8-hascontext-trait

⇱ HasContext Trait | hypervel/api-client | DeepWiki


Loading...
Menu

HasContext Trait

The HasContext trait provides a mechanism for attaching and retrieving arbitrary contextual metadata to objects throughout the request/response lifecycle. This trait is used by both ApiRequest and ApiResponse classes to enable passing additional data that isn't part of the standard HTTP message structure.

For information about how context is used during middleware execution, see Middleware System and Context Management.

Overview

The HasContext trait implements a simple key-value store that allows objects to carry metadata alongside their primary data. This is particularly useful for:

  • Passing metadata through middleware pipelines
  • Storing request identifiers or correlation IDs
  • Maintaining debugging or logging information
  • Carrying custom application-specific data

The trait is implemented in src/HasContext.php1-38 and provides two core methods for managing contextual data.

Sources: src/HasContext.php1-38

Trait Definition


Sources: src/HasContext.php7-38

Methods

withContext()

The withContext() method sets contextual data on the object and returns the object instance for method chaining.

Signature: public function withContext(string|array $key, mixed $value = null): static

Behavior:

Parameter TypeBehaviorImplementation
arrayMerges the provided array with existing contextsrc/HasContext.php16-19
stringSets a single key-value pairsrc/HasContext.php21-24

The method implementation at src/HasContext.php14-25 demonstrates two usage patterns:

  1. Single key-value: When $key is a string, it sets $context[$key] = $value
  2. Batch assignment: When $key is an array, it merges with existing context using array_merge()

The method returns static, enabling fluent method chaining with the object.

Sources: src/HasContext.php11-25

context()

The context() method retrieves contextual data from the object.

Signature: public function context(?string $key = null): mixed

Behavior:

ParameterReturn ValueImplementation
nullReturns entire context arraysrc/HasContext.php36
stringReturns value for specific key, or null if not foundsrc/HasContext.php32-33

The implementation at src/HasContext.php30-37 uses nullable parameter typing to support both retrieval patterns within a single method.

Sources: src/HasContext.php27-37

Storage Structure


The context is stored as a protected array property at src/HasContext.php9 This design choice ensures:

  • Context data is accessible to the class using the trait and its subclasses
  • Direct external access is prevented, enforcing use of the trait methods
  • Context persists throughout the object's lifetime

Sources: src/HasContext.php9

Integration Points

The HasContext trait is integrated into the API client system at two critical points in the request/response lifecycle:


According to the high-level architecture diagrams, both ApiRequest and ApiResponse use the HasContext trait. Since ApiResource stores both the request and response objects, context data remains accessible throughout the entire lifecycle.

Sources: src/HasContext.php7-38

Data Flow Example

The following diagram illustrates how context flows through a typical request:


Sources: src/HasContext.php1-38

Implementation Details

Protected Property

The context storage uses a protected array property src/HasContext.php9:

protected array $context = [];

This visibility level ensures:

  • Subclasses can access context directly if needed
  • External code must use the public methods
  • Context is initialized as an empty array

Type Handling

The trait uses PHP's type system effectively:

FeatureImplementationLocation
Union typesstring|array $keysrc/HasContext.php14
Nullable types?string $key = nullsrc/HasContext.php30
Return typestatic for fluent interfacesrc/HasContext.php14
Mixed returnmixed for flexible valuessrc/HasContext.php30

Array Merging Strategy

When setting context with an array, the implementation uses array_merge() at src/HasContext.php17:

$this->context = array_merge($this->context, $key);

This merge strategy means:

  • New keys are added to existing context
  • Existing keys are overwritten with new values
  • Numeric keys are re-indexed

Sources: src/HasContext.php9-37

Common Usage Patterns

Pattern 1: Request Identification

// Context added to request
$request->withContext('correlation_id', $uuid);

// Retrieved in middleware
$correlationId = $request->context('correlation_id');

Pattern 2: Batch Context Assignment

// Multiple context values set at once
$request->withContext([
 'user_id' => 123,
 'tenant_id' => 'acme',
 'trace_id' => 'xyz789',
]);

// All context retrieved
$allContext = $request->context(); // Returns full array

Pattern 3: Method Chaining

// Fluent interface with context setting
$request
 ->withContext('feature_flag', 'enabled')
 ->withHeader('Authorization', $token)
 ->withContext('attempt', 1);

Sources: src/HasContext.php14-37

Design Considerations

Trait vs. Interface

The implementation uses a trait rather than an interface because:

  • It provides concrete implementation, not just a contract
  • Both ApiRequest and ApiResponse need identical context handling
  • The storage mechanism ($context array) is shared

Immutability Pattern

While withContext() returns static suggesting immutability, the method actually mutates the object at src/HasContext.php17 and src/HasContext.php22 This is a practical design choice that:

  • Enables fluent method chaining
  • Avoids excessive object cloning
  • Maintains performance in the middleware pipeline

Null Handling

The context() method returns null for missing keys at src/HasContext.php33 rather than throwing exceptions. This design:

  • Provides graceful handling of optional context
  • Follows PHP's null-coalescing patterns
  • Simplifies middleware implementation

Sources: src/HasContext.php1-38

Related Components

ComponentRelationshipReference
ApiRequestUses HasContext for request metadataSee ApiRequest
ApiResponseUses HasContext for response metadataSee ApiResponse
Middleware SystemAccesses context during processingSee Middleware Overview
PendingRequestOrchestrates context-aware objectsSee PendingRequest

Sources: src/HasContext.php1-38