Search by

fiberphp / context

fiberphp

🧵 FiberPHP 请求级上下文容器 —— 基于 Workerman Coroutine 上下文、Fiber 隔离、销毁回调(onDestroy)。

v0.1.0 2026-11-22 10:55 UTC

This package is auto-updated.

Last update: 2026-11-22 10:55:51 UTC


README

请求级上下文容器:按 Fiber 隔离数据,scope 成对包裹请求生命周期,销毁时按注册逆序执行资源回收回调。

环境要求

  • PHP >= 8.5
  • workerman/coroutine ^1.1

安装

composer require fiberphp/context

快速上手

use ArrayObject;
use FiberPHP\Context\Context;

Context::startScope(new ArrayObject(['request_id' => 'req-1']));

try {
    Context::set('user_id', 42);

    Context::get('request_id');        // 'req-1'
    Context::get('missing', '默认值');  // '默认值'
    Context::has('user_id');           // true
} finally {
    Context::endScope();
}

startScope() 在 try 块开头调用,endScope() 放在 finally 中;endScope() 幂等,未开启 scope 时调用也不会报错。

数据读写

方法说明
Context::get(?string $name = null, mixed $default = null): mixed传入 $name 返回对应值或默认值;不传返回当前上下文的 ArrayObject
Context::set(string $name, mixed $value): void写入当前上下文
Context::has(string $name): bool判断键是否存在
Context::reset(?ArrayObject $data = null): void重置上下文,可附带初始数据;重置前会触发已注册的销毁回调
Context::destroy(): void立即销毁当前上下文,触发销毁回调并清空数据
$all = Context::get();

$all['tenant_id'];  // 数组访问
$all->tenant_id;    // 属性访问

请求 scope

方法说明
Context::startScope(?ArrayObject $initialData = null): void开启 scope 并写入初始数据;已有 scope 时先结束旧 scope,旧数据与销毁回调随之清理
Context::endScope(): void结束当前 scope,等效于 destroy()
Context::isScoped(): bool当前执行环境是否处于 scope 中

销毁回调

use FiberPHP\Context\Context;

Context::onDestroy(static function (): void {
    // 归还连接、关闭句柄等资源回收
});
  • onDestroy(Closure $closure): void 把回调注册到当前上下文,endScope() / reset() / destroy() 或 Fiber 结束时触发。
  • 多个回调按注册逆序执行。
  • 单个回调抛出的异常不会中断其余回调,失败信息写入 PHP 错误日志。
  • 回调执行时上下文正在销毁,不应再读写上下文;需要的数据在注册时用闭包捕获。

协程隔离

每个 Fiber 拥有独立上下文,互不串数据;未处于 Fiber 时使用进程级存储:

use ArrayObject;
use Fiber;
use FiberPHP\Context\Context;

$fiber = new Fiber(static function (): void {
    Context::startScope(new ArrayObject(['user' => 'alice']));

    Context::get('user');  // 'alice'
    Context::endScope();
});

$fiber->start();

Fiber 未调用 endScope() 就结束(或对象被回收)时,已注册的销毁回调仍会执行。

测试

composer test

单元测试覆盖数据读写、scope 开关、销毁回调与 Fiber 隔离;无外部服务依赖。

与其它包的关系

  • fiberphp/http 按请求划分 scope,fiberphp/framework 负责 scope 的开启与结束。
  • fiberphp/database 用 onDestroy 归还连接,异常路径同样触发;fiberphp/log 的 Context/Tracing processor 读取当前上下文。
  • 独立使用时需成对调用 startScope() / endScope(),或统一用 run()。

License

MIT