Context コルーチンコンテキスト

Contextはコルーチン内でコンテキスト情報を保存および伝達するために使用されます。たとえば、データベース接続やユーザー情報などです。各コルーチンは独自のコンテキストを持ち、異なるコルーチン間のコンテキストは隔離されています。

注意
低レベルで自動的にドライバタイプを識別し、Swoole/Swow/Fiberドライバのみをサポートします。

ヒント
この機能は 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; // または Swow::class または Fiber::class

$worker->onMessage = function (TcpConnection $connection, Request $request) {
    // 現在のコルーチンでcontextデータを設定
    Context::set('user_info', ['id' => 1, 'name' => 'name']);
    // 新しいコルーチンを作成
    Coroutine::create(function () use ($connection) {
        // コルーチン間のcontextデータは隔離されているため、新しいコルーチン内で取得するのはnull
        $userInfo = Context::get('user_info');
        var_dump($userInfo); // nullを出力
    });
    // 現在のコルーチンのcontextデータを取得
    $userInfo = Context::get('user_info'); // ['id' => 1, 'name' => 'name'] を取得
    $connection->send(json_encode($userInfo));
};

Worker::runAll();

インターフェース説明

interface ContextInterface
{
    /**
     * コンテキストから値を取得
     */
    public static function get(string $name, mixed $default = null): mixed;

    /**
     * コンテキストに値を設定
     */
    public static function set(string $name, mixed $value): void;

    /**
     * コンテキストに指定名称の値が存在するか確認
     */
    public static function has(string $name): bool;

    /**
     * 現在のコルーチンコンテキストをリセット
     */
    public static function reset(?ArrayObject $data = null): void;

    /**
     * コンテキストを破棄
     */
    public static function destroy(): void;

}