Context

The Context is used to store and pass context information within coroutines, such as database connections, user information, etc. Each coroutine has its own context, and the contexts of different coroutines are isolated.

Note
The underlying driver type is automatically recognized and only supports Swoole/Swow/Fiber drivers.

Tip
This feature requires workerman >= 5.1.0

<?php

use Workerman\Connection\TcpConnection;
use Workerman\Coroutine;
use Workerman\Coroutine\Context;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('http://0.0.0.0:8001');

$worker->eventLoop = Swoole::class; // Or Swow::class or Fiber::class

$worker->onMessage = function (TcpConnection $connection, Request $request) {
    // Set context data in the current coroutine
    Context::set('user_info', ['id' => 1, 'name' => 'name']);
    // Create a new coroutine
    Coroutine::create(function () use ($connection) {
        // Context data is isolated between coroutines, so the new coroutine retrieves null
        $userInfo = Context::get('user_info');
        var_dump($userInfo); // Outputs null
    });
    // Retrieve the context data of the current coroutine
    $userInfo = Context::get('user_info'); // Gets ['id' => 1, 'name' => 'name']
    $connection->send(json_encode($userInfo));
};

Worker::runAll();

Interface Description

interface ContextInterface
{
    /**
     * Get the value from the context
     */
    public static function get(string $name, mixed $default = null): mixed;

    /**
     * Set the value in the context
     */
    public static function set(string $name, mixed $value): void;

    /**
     * Check if a value with a given name exists in the context
     */
    public static function has(string $name): bool;

    /**
     * Reset the current coroutine context
     */
    public static function reset(?ArrayObject $data = null): void;

    /**
     * Destroy the context
     */
    public static function destroy(): void;

}