Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Context Laravel Package

hyperf/context

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require hyperf/context
    

    Ensure your composer.json includes "hyperf/context": "^3.0" for stability.

  2. 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');
    
  3. Where to Look First:

    • Source Code (focus on Context.php and ApplicationContext.php).
    • Tests for usage examples (e.g., ContextTest.php).
    • Hyperf Docs for coroutine context integration with Hyperf’s ecosystem.

Implementation Patterns

Core Workflows

  1. 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');
    
  2. 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...
    });
    
  3. Dependency Injection: Bind context values to services via Hyperf’s container:

    $container->set('user.repository', fn() => new UserRepository(
        Context::get('user_id') // Injected dynamically
    ));
    

Integration Tips

  • Middleware: Attach context early in the request pipeline:
    public function process(MiddlewareContext $context): void
    {
        ApplicationContext::set('user', $context->user());
    }
    
  • Async Workers: Share context between workers using ApplicationContext (ensure same process group).
  • Testing: Mock context in tests:
    Context::shouldReceive('get')->andReturn($mockData);
    

Gotchas and Tips

Pitfalls

  1. Thread Safety:

    • Context is not thread-safe. Use ApplicationContext for multi-threaded scenarios (e.g., Hyperf workers).
    • Fix: Avoid sharing Context across threads; use ApplicationContext or explicit locks.
  2. Serialization:

    • Context values must be serializable. Non-serializable objects (e.g., closures, resources) will throw errors.
    • Fix: Use primitive types or implement Serializable/JsonSerializable.
  3. Lifetime Mismatches:

    • Values in Context persist only for the coroutine’s lifetime. ApplicationContext values may linger across requests if not cleared.
    • Fix: Explicitly clear values post-request:
      ApplicationContext::clear();
      
  4. Hyperf-Specific Quirks:

    • Context is not automatically shared between HTTP and RPC processes. Use ApplicationContext for cross-process sharing.
    • Fix: Pass critical data via RPC parameters or a shared store (e.g., Redis).

Debugging Tips

  • Inspect Context:
    dump(Context::all()); // Dump all context values
    
  • Enable Logging: Set HYPERF_CONTEXT_LOG_ENABLED=true in .env to log context operations.

Extension Points

  1. Custom Context: Extend 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);
        }
    }
    
  2. Event Listeners: Hook into context changes via Hyperf’s event system:
    Event::listen(ContextChanged::class, function ($event) {
        logger()->info("Context changed: {$event->key}");
    });
    
  3. Fallback Values: Use Context::get($key, $default) to avoid exceptions for missing keys.

Performance

  • Avoid Overuse: Context adds minimal overhead, but excessive use can bloat memory.
  • Benchmark: Test with 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`.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor