Context 协协上下文
Context ใช้ในการเก็บและส่งต่อข้อมูลบริบทใน coroutine เช่น การเชื่อมต่อฐานข้อมูล ข้อมูลผู้ใช้ เป็นต้น ทุกๆ coroutine จะมีบริบทของตัวเอง บริบทระหว่าง coroutine ที่แตกต่างกันจะถูกแยกออกจากกัน
注意
ระบบจะระบุประเภทไดร์เวอร์โดยอัตโนมัติ รองรับเฉพาะไดร์เวอร์ 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 ใน coroutine ปัจจุบัน
Context::set('user_info', ['id' => 1, 'name' => 'name']);
// สร้าง coroutine ใหม่
Coroutine::create(function () use ($connection) {
// ข้อมูล context ระหว่าง coroutine จะแยกออกจากกัน ดังนั้นใน coroutine ใหม่จึงได้ค่าเป็น null
$userInfo = Context::get('user_info');
var_dump($userInfo); // ผลลัพธ์เป็น null
});
// รับค่าข้อมูล context ใน coroutine ปัจจุบัน
$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;
/**
* รีเซ็ตบริบทของ coroutine ปัจจุบัน
*/
public static function reset(?ArrayObject $data = null): void;
/**
* ทำลายบริบท
*/
public static function destroy(): void;
}