Context
Context is a thread-safe context propagation primitive that carries request metadata, tracing identifiers, and worker attributes across asynchronous Fiber execution boundaries.
Concept
In stateful PHP execution, multiple Fibers run concurrently within the same OS process. Nexphant uses the Context store to guarantee that request-specific state (like trace IDs, logged-in user context, database transaction scopes) is isolated and correctly restored when a Fiber is suspended and resumed.
Context Fields
The RuntimeContext maintains standard telemetry fields:
- trace_id: Unique request identifier shared across all sub-fibers, jobs, and transactions.
- span_id: Unique identifier for the current trace block/segment.
- owner_id: The UUID of the current execution owner.
- owner_type: The type of owner (e.g.,
request,fiber,worker).
Basic Usage
You can retrieve the current context or run closures in isolated context boundaries:
Retrieving Current Context
use Nexphant\Runtime\Runtime;
// Get current RuntimeContext
$context = Runtime::context();
// Retrieve trace ID
$traceId = $context->traceId();
// Retrieve current owner
$ownerId = $context->ownerId();Context Isolation & Branching
Create a new context branch with updated parameters and run a task within it:
use Nexphant\Runtime\Runtime;
// Run code with modified context variables
$result = Runtime::withContext(['tenant_id' => 12], function () {
// Current context now contains 'tenant_id' => 12
$tenantId = Runtime::context()->get('tenant_id');
return doWork();
});Context Propagation
When spawning a coroutine using Runtime::spawn(), Nexphant automatically propagates the parent's context:
use Nexphant\Runtime\Runtime;
$parentTraceId = Runtime::traceId();
Runtime::spawn(function () use ($parentTraceId) {
// The child Fiber automatically inherits the parent's trace_id
$childTraceId = Runtime::traceId();
assert($parentTraceId === $childTraceId); // true
});