Installation:
composer require hyperf/context
Ensure your composer.json includes "hyperf/context": "^3.0" for stability.
First Use Case: Inject the context into a coroutine to share data across async boundaries:
use Hyperf\Context\Context;
use Hyperf\Context\ApplicationContext;
// Set context value
Context::set('user_id', 123);
// Retrieve in another coroutine
$userId = Context::get('user_id');
Where to Look First:
Context.php and ApplicationContext.php).ContextTest.php).Request-Scoped Context:
Use ApplicationContext to bind values to the current request lifecycle (e.g., user auth, request ID):
// Middleware or controller
ApplicationContext::set('request_id', uniqid());
// Later in a coroutine
$requestId = ApplicationContext::get('request_id');
Coroutine-Specific Context:
Use Context for values tied to a single coroutine (e.g., temporary processing state):
go(function () {
Context::set('temp_data', ['key' => 'value']);
// Coroutine logic...
});
Dependency Injection: Bind context values to services via Hyperf’s container:
$container->set('user.repository', fn() => new UserRepository(
Context::get('user_id') // Injected dynamically
));
public function process(MiddlewareContext $context): void
{
ApplicationContext::set('user', $context->user());
}
ApplicationContext (ensure same process group).Context::shouldReceive('get')->andReturn($mockData);
Thread Safety:
Context is not thread-safe. Use ApplicationContext for multi-threaded scenarios (e.g., Hyperf workers).Context across threads; use ApplicationContext or explicit locks.Serialization:
Serializable/JsonSerializable.Lifetime Mismatches:
Context persist only for the coroutine’s lifetime. ApplicationContext values may linger across requests if not cleared.ApplicationContext::clear();
Hyperf-Specific Quirks:
ApplicationContext for cross-process sharing.dump(Context::all()); // Dump all context values
HYPERF_CONTEXT_LOG_ENABLED=true in .env to log context operations.ContextManager to add namespaces or validation:
class CustomContext extends ContextManager
{
public function set(string $key, $value, string $namespace = 'custom'): void
{
$this->store->set("{$namespace}.{$key}", $value);
}
}
Event::listen(ContextChanged::class, function ($event) {
logger()->info("Context changed: {$event->key}");
});
Context::get($key, $default) to avoid exceptions for missing keys.hyperf context:benchmark (if available) to measure impact.
```markdown
---
**Note**: While this package is designed for Hyperf, Laravel developers can adapt patterns (e.g., request-scoped context) using Laravel’s `app()` binding or packages like `spatie/laravel-context`. For coroutine support, consider `laravel-async` or `reactphp`.
How can I help you explore Laravel packages today?