fiberphp / http
FiberPHP HTTP 子系统:基于 Workerman 协议实现请求/响应/中间件,集成 Pipeline 协程管道与 Context 协程隔离
Requires
- php: >=8.3
- fiberphp/framework: dev-master
Requires (Dev)
- phpunit/phpunit: ^11.0
This package is auto-updated.
Last update: 2026-08-22 10:11:55 UTC
README
FiberPHP 框架的 HTTP 子系统。基于 Workerman 协议层实现请求/响应/中间件,集成 Pipeline 协程管道与 Context 协程隔离,每个请求在独立 Fiber 中执行,中间件内可安全挂起做异步 I/O。
特性
- 协程隔离:每个请求
startScope开启独立 Context,endScope必清理,防跨请求泄漏 - Pipeline 管道:全局中间件按声明顺序串接,支持
Fiber::suspend()挂起/恢复 - 中间件双源:
config/http.php显式声明 +#[Package(middleware: [...])]子包声明,自动合并去重 - 异常兜底:
Handler优先App\ExceptionHandler,基类renderHttp()按 BusinessException / Exception / Throwable 分层渲染 - 响应策略:keep-alive / chunked / close 自动判定,支持 If-Modified-Since 304 协商缓存
- URI 安全:拦截路径穿越(
/../、\、\0)、空路径、反斜杠 - 辅助函数:
request()/input()/response()/json()/xml()/redirect()
环境要求
- PHP >= 8.3
ext-jsonext-mbstringfiberphp/frameworkdev-master
安装
composer require fiberphp/http
安装后 PackageInstaller::discover 自动把 config/http.php 和 config/process/http.php 拷贝到应用 config/(幂等不覆盖),并通过 PackageManifest 注册 HttpProvider。
配置
config/http.php — 全局中间件
return [
'middleware' => [
// \App\Middleware\Cors::class,
// \App\Middleware\Auth::class,
],
];
中间件类需实现 FiberPHP\Http\Contract\MiddlewareInterface 的 process(Request, callable): Response 方法。
config/process/http.php — Worker 进程
return [
'http' => [
'enable' => true,
'handler' => Http::class,
'listen' => 'http://0.0.0.0:8787',
'count' => max(1, cpu_count()),
'constructor' => [
'requestClass' => Request::class,
'logger' => static fn () => logger()->channel('default'),
],
],
];
请求生命周期
onMessage
├─ Context::startScope(Request) // 开启协程 scope,注入 Request
├─ unsafeUri() // 拦截路径穿越 → 400/404
├─ Pipeline::build(middleware, handler) // 串接中间件 + handler
│ ├─ Middleware A::process()
│ ├─ Middleware B::process()
│ └─ RequestHandlerInterface::handle() // 路由分发(fiberphp/router 提供)
├─ Http::send(connection, response) // keep-alive/chunked/close
└─ Context::endScope() // 清理 scope + onDestroy 回调
使用
请求参数
// 获取全部参数
$params = request()->all();
// 单个参数(先 GET 后 POST,缺失返回默认值)
$id = request()->input('id', 0);
// 仅取 / 排除指定键
$data = request()->only(['name', 'email']);
$data = request()->except(['password']);
响应构造
// 纯文本
return response('hello');
// JSON
return json(['code' => 0, 'data' => $list]);
// XML
return xml($xmlElement);
// 重定向
return redirect('/login');
// 链式调用
return response('OK')
->withHeaders(['X-Trace-Id' => $traceId])
->withStatus(200);
文件响应
// 静态文件(命中 If-Modified-Since 返回 304)
return response()->file('/path/to/file.txt');
// 浏览器下载
return response()->download('/path/to/report.pdf', '月度报告.pdf');
上传文件
$file = request()->file('avatar');
if ($file->isValid()) {
$tmpPath = $file->getFileName(); // 临时文件路径
$originalName = $file->getUploadName(); // 客户端原始文件名
$extension = $file->getUploadExtension(); // 扩展名
// 业务侧自行处理 move_uploaded_file / SplFileObject
}
客户端 IP
// 直连 IP
$ip = request()->getRemoteIp();
// 真实 IP(safeMode 下仅信任内网代理头)
$ip = request()->getRealIp(); // safeMode=true(默认)
$ip = request()->getRealIp(false); // 信任所有代理头
请求判定
request()->isGet();
request()->isPost();
request()->isAjax();
request()->isPjax();
request()->expectsJson(); // AJAX 非 PJAX 或 Accept: json
中间件
namespace App\Middleware;
use FiberPHP\Http\Contract\MiddlewareInterface;
use FiberPHP\Http\Request;
use FiberPHP\Http\Response;
class Auth implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$token = $request->header('Authorization');
if (!$token) {
return json(['code' => 401, 'msg' => 'Unauthorized'], 401);
}
return $handler($request); // 传递给下一层
}
}
注册到 config/http.php:
'middleware' => [
\App\Middleware\Auth::class,
],
路由 handler
未安装 fiberphp/router 时,在容器中绑定 RequestHandlerInterface 实现自定义调度:
// App\Provider 中
$container->singleton(RequestHandlerInterface::class, MyHandler::class);
安装 fiberphp/router 后,默认 handler 自动接管路由分发。
异常处理
HTTP 异常渲染分层:
| 异常类型 | HTTP 状态码 | 说明 |
|---|---|---|
NotFoundException | 404 | 路由未找到 |
InputException | 400 | 输入参数校验失败 |
BusinessException 派生 | 自定义 | 业务异常 |
其他 Throwable | 500 | 服务端错误 |
debug=true 时响应体附带 file / line / trace(debugAware=true 的异常始终附带)。
应用可创建 App\ExceptionHandler 继承 FiberPHP\Http\Exception\Handler,覆盖 renderHttp() 实现自定义渲染。
License
MIT