VOOZH about

URL: https://deepwiki.com/hypervel/api-client/8.1-context-management

⇱ Context Management | hypervel/api-client | DeepWiki


Loading...
Menu

Context Management

Purpose and Scope

This document explains the context management system provided by the HasContext trait, which enables attaching arbitrary metadata to ApiRequest and ApiResponse objects throughout the request/response lifecycle. Context data is useful for passing information between middleware, tracking request identifiers, or storing diagnostic information without modifying core data structures.

For information about middleware configuration options that can be passed per-request, see Middleware Configuration. For general request configuration, see Request Configuration.


The HasContext Trait

The HasContext trait provides a simple key-value storage mechanism for associating metadata with objects. It is used by both ApiRequest and ApiResponse classes to enable contextual data management throughout the request/response lifecycle.

Trait Structure


Sources: src/HasContext.php1-38 src/ApiRequest.php14 src/ApiResponse.php12

Storage Mechanism

The trait maintains an internal associative array to store context data:

PropertyTypeVisibilityPurpose
$contextarrayprotectedStores key-value pairs of contextual data

Sources: src/HasContext.php9


Setting Context Data

Context data can be set using the withContext() method, which supports two distinct patterns for maximum flexibility.

Method Signature


Sources: src/HasContext.php14-25

Single Key-Value Pattern

The method accepts a string key and a value to set a single context entry:

  • Parameters: withContext(string $key, mixed $value)
  • Behavior: Sets $this->context[$key] = $value
  • Returns: static (for method chaining)

Example reference: src/HasContext.php22-24

Array Merge Pattern

The method can accept an array to set multiple context entries at once:

  • Parameters: withContext(array $key, mixed $value = null)
  • Behavior: Merges the array into existing context using array_merge()
  • Returns: static (for method chaining)

Example reference: src/HasContext.php16-19

Fluent Interface Support

Both patterns return static, enabling fluent method chaining. The context can be set alongside other request or response configuration methods.

Sources: src/HasContext.php14-25


Retrieving Context Data

The context() method provides read access to stored context data with support for retrieving specific keys or the entire context array.

Retrieval Patterns


Sources: src/HasContext.php30-37

Accessing Specific Keys

When called with a string key parameter:

  • Parameters: context(string $key)
  • Returns: The value stored at $this->context[$key], or null if not set
  • Behavior: Uses null coalescing operator for safe access

Example reference: src/HasContext.php32-33

Accessing All Context

When called without parameters:

  • Parameters: context()
  • Returns: The entire $this->context array
  • Behavior: Direct array return

Example reference: src/HasContext.php36

Sources: src/HasContext.php30-37


Context Availability in the Request/Response Lifecycle

Context is available on both ApiRequest and ApiResponse objects, enabling metadata to persist throughout the entire request/response lifecycle.

Component Integration


Sources: src/ApiRequest.php12-14 src/ApiResponse.php10-12

Context Independence

Each ApiRequest and ApiResponse maintains its own independent context storage:

ObjectContext ScopeLifecycle
ApiRequestRequest-specific metadataFrom creation until HTTP execution
ApiResponseResponse-specific metadataFrom HTTP response until resource transformation

The contexts are not automatically synchronized or merged between request and response objects. If context needs to be transferred from request to response, this must be done explicitly in middleware or application code.

Sources: src/HasContext.php9 src/ApiRequest.php14 src/ApiResponse.php12


Context Data Flow Through the System

Context data flows through the request/response lifecycle, providing access points at multiple stages for reading and writing metadata.

Lifecycle Sequence


Sources: src/HasContext.php1-38 src/ApiRequest.php14 src/ApiResponse.php12

Access Points

Context can be read or written at the following points:

  1. Application Code: Before sending the request via PendingRequest
  2. Request Middleware: During request processing pipeline
  3. Response Middleware: During response processing pipeline
  4. Between Stages: Middleware can transfer context from request to response

Sources: src/HasContext.php1-38


Common Use Cases

Request Tracking and Correlation

Context enables request correlation across distributed systems:


Middleware can then read these identifiers for logging, tracing, or propagating to downstream services.

Middleware Communication

Context provides a communication channel between middleware layers:


Debugging and Diagnostics

Context stores diagnostic information without affecting request/response data:


Transferring Data from Request to Response

Middleware can copy relevant context from request to response:


Sources: src/HasContext.php1-38


Working with Context

Context Immutability Pattern

The withContext() method follows an immutable pattern, returning static to enable method chaining while maintaining the object's fluent interface:


Note: While the method returns $this, the context array itself is mutable. The pattern supports fluent chaining, not true immutability.

Sources: src/HasContext.php14-25

Chaining Context with Other Methods

Context methods integrate seamlessly with other fluent methods on ApiRequest and ApiResponse:


Sources: src/ApiRequest.php14 src/ApiResponse.php12 src/HasContext.php14-25

Null Safety

The context() getter method uses null coalescing to safely handle missing keys:

  • Missing key returns: null instead of throwing exceptions
  • Pattern: $this->context[$key] ?? null
  • Benefit: No need for isset() checks before access

Sources: src/HasContext.php32-33

Memory Considerations

Context data persists for the lifetime of the ApiRequest or ApiResponse object. Consider the following:

ConsiderationRecommendation
Large dataAvoid storing large objects or arrays in context
Sensitive dataBe cautious about storing credentials or PII
CleanupContext is automatically garbage collected with the object

Context is stored in memory for the duration of the object's lifecycle and is not persisted beyond that.

Sources: src/HasContext.php9


Implementation Details

Trait Design

The HasContext trait provides implementation without dependencies, making it reusable across different classes:


Sources: src/HasContext.php7-38

Method Signatures

MethodParametersReturn TypePurpose
withContextstring|array $key, mixed $value = nullstaticSet context data
context?string $key = nullmixedGet context data

Sources: src/HasContext.php14-37

Protected Storage

The $context array is marked protected, allowing:

  • Encapsulation: Context is not directly accessible from outside
  • Inheritance: Subclasses can access context if needed
  • Controlled Access: Only through withContext() and context() methods

Sources: src/HasContext.php9