kode / http
现代化、高性能的 PHP HTTP 服务端库,支持 PSR-7/PSR-15/PSR-17 标准,多运行时环境(Swoole、Workerman、FPM),深度集成 kode/process、kode/fibers、kode/parallel
Requires
- php: ^8.3
- kode/context: ^3.1
- kode/exception: ^3.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.0|^2.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- guzzlehttp/psr7: ^2.1
- kode/facade: ^3.2
- kode/fibers: ^4.10
- kode/parallel: ^1.18
- kode/process: ^5.2
- kode/queue: ^2.2
- phpunit/phpunit: ^10.0|^11.0|^12.0
- swoole/ide-helper: ^4.15|^5.0
- symfony/var-dumper: ^6.0|^7.0
Suggests
- ext-swoole: 用于 Swoole 协程支持和异步 HTTP 服务器
- guzzlehttp/psr7: 用于 PSR-7 消息实现参考
- kode/facade: 用于服务门面与协程安全(context-safe)的服务解析(最新 3.x,Kode 容器已原生接入)
- kode/fibers: 用于 Fiber 协程调度和并发处理(最新 4.x,作为并发引擎被 Integration 中间件优先使用)
- kode/parallel: 用于并行任务执行和多线程支持(最新 1.x,需 ZTS + ext-parallel,ParallelMiddleware 优先使用)
- kode/process: 用于进程池管理和 Worker 进程(最新 5.x,ProcessWorkerMiddleware 可接管真实进程池)
- kode/queue: 用于后台任务队列(最新 2.x,QueueMiddleware 在响应后统一派发收集的任务)
- kode/runtime: 用于协程运行时抽象
- workerman/workerman: 用于 Workerman 多进程支持
README
现代化、高性能的 PHP HTTP 服务端库
Kode\Http 是一个专为 PHP 8.3+ 设计的高性能 HTTP 服务端库,完全兼容 PSR-7/PSR-15/PSR-17 标准。支持 Swoole、Workerman 等协程环境,支持分布式部署,深度集成
kode/context、kode/exception、kode/fibers、kode/parallel、kode/process,打造现代化全栈 PHP 应用。设计理念:借鉴 ThinkPHP/Laravel/webman 的简洁风格,提供
Request、Response、App三大核心 API,让开发者无需心智负担即可快速构建高性能 HTTP 服务。
核心特性
- 📦 简洁 API:
Request、Response、App三剑客 - 🎯 PSR-7/15/17 完全兼容:标准化的 HTTP 消息、中间件和工厂实现
- ⚡ 高性能协程支持:无缝对接 Swoole/Workerman,支持 Fiber 协程
- 🔄 多运行时适配:自动检测并适配 FPM、CLI、Swoole、Workerman 环境
- 🌐 分布式部署支持:支持跨机器 Worker、Fiber、并行任务分发
- 🧩 模块化中间件:灵活的中间件管道,支持链式调用
- 🔗 深度集成:与
kode/context、kode/process、kode/fibers、kode/parallel无缝协作 - 🛡️ 企业级特性:CORS、限流、错误处理、进程管理等开箱即用
环境要求
| 环境 | 版本要求 |
|---|---|
| PHP | >= 8.3 |
| PSR-7 | ^1.0 或 ^2.0 |
| PSR-15 | ^1.0 |
| PSR-17 | ^1.0 |
可选扩展
| 扩展 | 说明 |
|---|---|
ext-swoole |
Swoole 协程支持和异步 HTTP 服务器 |
ext-fiber |
PHP Fiber 协程支持 |
workerman/workerman |
Workerman 多进程支持 |
快速开始
安装
composer require kode/http
最简示例
<?php require 'vendor/autoload.php'; use Kode\Http\App; use Kode\Http\Request; use Kode\Http\Response; $app = App::create(); $app->get('/api/hello', function() { $name = Request::get('name', 'World'); return Response::success(['greeting' => "你好,{$name}!"]); }); $app->serve(8080);
核心 API
Request - 请求解析(借鉴 webman)
无需传入 request 参数,直接获取当前请求
// 参数获取(自动从当前请求获取) Request::get('name'); // GET 参数 Request::post('name'); // POST 参数 Request::json('name'); // JSON body 参数 Request::header('Authorization'); // 请求头 Request::cookie('session_id'); // Cookie // 字段选择(借鉴 Laravel) Request::only('name', 'email'); // 仅获取指定字段 Request::except('password', 'token'); // 排除指定字段 // 判断存在(借鉴 ThinkPHP) Request::has('name'); // 参数是否存在 Request::missing('token'); // 参数是否缺失 // 获取所有参数 Request::all(); // 合并 query + body // 请求信息 Request::ip(); // 客户端 IP Request::method(); // 请求方法 Request::path(); // 请求路径 Request::isAjax(); // 是否 AJAX 请求 Request::isJson(); // 是否 JSON 请求 Request::isMobile(); // 是否移动端 Request::isGet(); // 是否 GET 请求 Request::isPost(); // 是否 POST 请求 // 其他 Request::userAgent(); // User-Agent Request::referer(); // 来源页面 Request::language(); // Accept-Language Request::time(); // 请求时间戳 Request::file('avatar'); // 上传文件 Request::server('REQUEST_TIME'); // 服务器变量
Response - 响应构建(链式调用,且本身是真实 PSR-7)
Kode\Http\Response自 v3.3 起直接继承真实 PSR-7 实现,工厂方法与辅助方法合二为一:Response::json()/error()/success()/fail()返回的就是真实 PSR-7 响应, 因此中间件/处理器里可直接return,无需再调用->send()(->send()保留为向后兼容的空操作)。
// JSON 响应(直接 return,无需 ->send()) return Response::json(['data' => 'value']); return Response::json(['data' => 'value'], 1); // 带业务码 // 业务响应(借鉴 Laravel) return Response::success(['id' => 1], '操作成功'); return Response::fail('用户名或密码错误', 'E1001'); // HTTP 错误 return Response::error(404, 'Not Found'); return Response::error(500, 'Internal Server Error', 'E1500'); // 其他响应类型 return Response::text('Hello World'); return Response::html('<h1>Title</h1>'); return Response::xml('<root></root>'); return Response::empty(); // 204 空响应 return Response::redirect('/login'); // 302 重定向 return Response::download('/path/file.pdf'); // 链式调用(cookie / CORS / 安全头等都是 PSR-7 上的方法) return Response::success(['data' => $data]) ->status(201) ->header('X-Custom', 'value') ->withCors() ->withCache(3600) ->withSecurity() ->cookie('token', $jwt, httpOnly: true);
App - 应用构建器
use Kode\Http\App; use Kode\Http\Request; use Kode\Http\Response; $app = App::create(debug: true); // 添加中间件 $app->use(function($req, $next) { $start = microtime(true); $response = $next->handle($req); return $response->withHeader('X-Execution-Time', sprintf('%.2fms', (microtime(true) - $start) * 1000)); }); // 路由注册 $app->get('/api/users', function() { return Response::success(['users' => [ ['id' => 1, 'name' => '张三'], ['id' => 2, 'name' => '李四'], ]]); }); $app->post('/api/users', function() { $name = Request::json('name'); $email = Request::json('email'); if (empty($name)) { return Response::fail('用户名不能为空', 'E1001', 400); } return Response::success(['id' => rand(1000, 9999)], '创建成功'); }); // 路由参数 $app->get('/api/users/{id}', function() { $id = Request::param('id'); // 路由参数(等价 Request::attr('id')) return Response::success(['id' => $id]); }); $app->delete('/api/users/{id}', function() { return Response::success(null, '删除成功'); }); // 路由组 $app->group('/api/v1', function($api) { $api->get('/status', fn() => Response::success(['status' => 'ok'])); $api->post('/action', fn() => Response::success()); }); // HTTP 方法 $app->patch('/api/users/{id}', fn() => Response::success()); $app->options('/api/users', fn() => Response::empty()); $app->any('/api/health', fn() => Response::success()); // 运行 $app->serve(8080);
PSR-7 消息实现
| 类 | 说明 |
|---|---|
Request |
HTTP 请求消息,包含方法、URI、头部、协议版本 |
Response |
HTTP 响应消息,包含状态码、原因短语、头部、正文 |
ServerRequest |
服务端请求,继承 Request 并添加服务端特性 |
Stream |
流式正文,支持读取、写入、定位等操作(自研实现);create() 对 ≤1MB 返回纯内存 StringStream |
StringStream |
纯内存流(v3.4.7),持有字符串直接返回、无 fopen/拷贝开销,isWritable()/isSeekable() 返回 false |
Uri |
URI 实现,支持解析和构建 URI 各部分 |
v3.4 起消息语义变更(契约级):
Request/Response/ServerRequest的with*方法 原地修改并返回自身(仿 webman / hyperf),不再克隆。即$a === $a->withHeader(...), 且$a->withHeader(...)会改$a本身。这消除了中间件管道逐层改消息时的对象分配。 若需独立快照请显式clone $msg。Uri仍保持 PSR-7 不可变语义。约定:中间件「只用返回值、不在中间件之间持有消息引用」,避免可变语义导致的隐蔽串改。
PSR-15 中间件
v3.4 起中间件管道为无状态、可重入、零逐请求分配实现:
MiddlewarePipeline在首次handle()时将中间件栈预编译为一个内部闭包链(洋葱模型),之后每请求直接复用,不再逐层new游标、不再有递归调用栈。管道对象本身只持有「中间件栈 + 最终处理器」,同一实例可在 Swoole 协程 / Fiber 并发环境下安全复用。
| 中间件 | 说明 |
|---|---|
MiddlewareDispatcher |
核心中间件调度器,管理中间件栈并执行调度 |
MiddlewarePipeline |
无状态管道实现,首次 handle 预编译闭包链、支持链式调用 |
CallableMiddleware |
将可调用对象转换为中间件 |
CorsMiddleware |
CORS 跨域处理 |
RateLimitMiddleware |
请求限流 |
JsonErrorHandlerMiddleware |
JSON 错误处理 |
BodyParser |
自动解析 JSON / 表单 / XML 请求体(PHP 8.3 json_validate) |
RequestId |
生成 / 复用请求 ID(X-Request-Id),便于链路追踪 |
ResponseTime |
注入 X-Response-Time 响应耗时头(hrtime 纳秒计时) |
Compression |
按 Accept-Encoding 协商 gzip / deflate 压缩响应体 |
SecurityHeaders |
注入 X-Content-Type-Options / X-Frame-Options / Referrer-Policy 等安全头 |
集成组件
| 组件 | 说明 |
|---|---|
ProcessWorkerMiddleware |
进程工作单元,集成 kode/process(≥5.x),支持分布式,可接管真实进程池 |
FiberCoroutineMiddleware |
Fiber 协程,集成 kode/fibers(≥4.x)作为统一并发引擎,支持分布式 |
ParallelMiddleware |
并行处理,集成 kode/parallel(≥1.x),支持分布式 |
QueueMiddleware |
队列派发,集成 kode/queue(≥2.x),处理器返回后统一派发收集的任务 |
并发引擎优先级(均可优雅降级):
ParallelMiddleware优先使用kode/parallel(需 ZTS + ext-parallel 真多线程),其次kode/fibers统一并发门面,最后回退原生\Fiber;FiberCoroutineMiddleware优先kode/fibers::concurrent+ 逐任务重试,回退原生\Fiber。kode/fibers/kode/parallel/kode/process/kode/queue均为可选依赖(已纳入require-dev与suggest),未安装时自动降级,不影响基础功能。
服务容器与门面(kode/facade 集成)
Kode 本身实现 PSR-11 容器接口,可无缝接入 kode/facade 的 FacadeProxy,并启用 context-safe 模式,在 Swoole / Fiber 协程环境下按请求(Context 作用域)隔离服务解析,避免跨协程串号:
use Kode\Http\Kode; use Kode\Http\Support\ServiceFacade; Kode::register('cache', new Cache()); Kode::enableFacades(); // 将 Kode 设为 kode/facade 后端容器并启用协程安全 final class Cache extends ServiceFacade { protected static function id(): string { return 'cache'; } } Cache::get('key'); // 经 Kode 容器解析,协程安全
队列派发(kode/queue 集成)
在路由处理器中收集后台任务,由 QueueMiddleware 在响应返回后统一派发,避免阻塞响应;任务收集基于 kode/context 请求作用域,天然协程安全:
use Kode\Http\Integration\QueueMiddleware; use Kode\Http\Queue\Queue; // bootstrap 中注入管理器(也可用 Queue::setManagerFromContainer($psr11)) Queue::setManager(\Kode\Queue\QueueManager::make([/* 连接配置 */])); $app->pipe(QueueMiddleware::fromContainer(Kode::container())); // 路由处理器内 Queue::push(SendMail::class, ['to' => $email]); // 仅收集,不阻塞响应
未配置 QueueManager 时自动懒加载内存驱动,便于本地开发与测试。
分布式部署
概述
Kode\Http 支持分布式部署场景,可以通过简单的配置启用分布式模式:
use Kode\Http\Integration\DistributedConfig; use Kode\Http\Integration\ProcessWorkerMiddleware; use Kode\Http\Integration\FiberCoroutineMiddleware; use Kode\Http\Integration\ParallelMiddleware;
分布式配置
$config = new DistributedConfig('node-1'); $config->setEnabled(true); $config->setNodes([ 'node-1' => ['host' => '192.168.1.1', 'port' => 8080, 'weight' => 1], 'node-2' => ['host' => '192.168.1.2', 'port' => 8080, 'weight' => 1], ]); $config->setLoadBalanceStrategy('round_robin'); $config->setCallTimeout(30.0); $config->setMaxRetries(3);
分布式 Worker(kode/process 集成)
$worker = new ProcessWorkerMiddleware(0, true, [ 'pool_size' => 4, 'enable_stats' => true, 'distributed' => [ 'enabled' => true, 'node_id' => 'worker-1', 'nodes' => [ 'worker-1' => ['host' => '192.168.1.1', 'port' => 8080], 'worker-2' => ['host' => '192.168.1.2', 'port' => 8080], ], ], ]); $app->use($worker);
分布式 Fiber 协程(kode/fibers 集成)
$fiber = new FiberCoroutineMiddleware(10, 2048, [ 'timeout' => 30, 'distributed' => [ 'enabled' => true, 'node_id' => 'fiber-1', 'nodes' => [ 'fiber-1' => ['host' => '192.168.1.1', 'port' => 8081], 'fiber-2' => ['host' => '192.168.1.2', 'port' => 8081], ], ], ]); $app->use($fiber);
分布式并行处理(kode/parallel 集成)
$parallel = new ParallelMiddleware(10, [ 'distributed' => [ 'enabled' => true, 'node_id' => 'parallel-1', 'nodes' => [ 'parallel-1' => ['host' => '192.168.1.1', 'port' => 8082], 'parallel-2' => ['host' => '192.168.1.2', 'port' => 8082], ], 'load_balance_strategy' => 'least_load', ], ]); $app->use($parallel);
项目结构
src/
├── Psr7/ # PSR-7 实现
│ ├── Message/ # 消息类(Request/Response/ServerRequest)
│ ├── Factory/ # PSR-17 工厂(含 Psr17Factory 聚合工厂)
│ ├── Trait/ # 可复用 Trait(RequestTrait/ResponseTrait)
│ ├── Stream.php # 自研流实现(create() 对小体返回 StringStream)
│ ├── StringStream.php # 纯内存流(v3.4.7,无 fopen/拷贝开销)
│ ├── Uri.php # URI 实现
│ └── UploadedFile.php # PSR-7 上传文件
├── Routing/ # 路由子系统
│ ├── Router.php # 静态哈希 + 动态正则两级匹配,区分 404/405
│ ├── Route.php # 路由定义(参数约束 / 可选参数 / 命名)
│ ├── RouteResult.php # 匹配结果(FOUND/NOT_FOUND/METHOD_NOT_ALLOWED)
│ └── RouteRunner.php # 路由执行器(最终处理器,参数注入 + 返回值归一化)
├── Middleware/ # PSR-15 中间件
│ ├── MiddlewareInterface.php
│ ├── MiddlewareDispatcher.php
│ ├── MiddlewarePipeline.php # 首次 handle 预编译为闭包链(洋葱模型),零逐请求分配
│ ├── CallableMiddleware.php
│ ├── CorsMiddleware.php
│ ├── RateLimitMiddleware.php
│ ├── JsonErrorHandlerMiddleware.php
│ ├── BodyParser.php # 请求体解析
│ ├── RequestId.php # 请求 ID
│ ├── ResponseTime.php # 响应耗时
│ ├── Compression.php # 响应压缩
│ └── SecurityHeaders.php # 安全响应头
├── Integration/ # 集成组件
│ ├── DistributedConfig.php
│ ├── ProcessWorkerMiddleware.php
│ ├── FiberCoroutineMiddleware.php
│ ├── ParallelMiddleware.php
│ └── QueueMiddleware.php # 队列派发(kode/queue)
├── Queue/ # 队列门面封装(kode/queue)
│ └── Queue.php # 按请求收集、统一派发的队列门面
├── Support/ # 支持组件
│ └── ServiceFacade.php # 协程安全的服务门面基类(kode/facade)
├── Server/ # 服务端适配器
├── Exception/ # 异常
├── App.php # 应用构建器
├── Request.php # 请求助手(kode/context 隔离)
├── Response.php # 响应助手(链式 + 返回值归一化)
├── Emitter.php # PSR-7 响应发射器(分块输出)
├── Status.php # HTTP 状态码枚举(类型安全 + 原因短语)
├── Method.php # HTTP 方法枚举(ROUTABLE/isSafe/isIdempotent)
├── Kode.php # 框架入口
└── functions.php # 辅助函数(指向 Psr17Factory)
测试
./vendor/bin/phpunit ./vendor/bin/phpunit --coverage-html coverage
与其他 Kode 包的关系
kode/http
│
├── kode/context # 请求上下文传递和管理(按请求隔离,协程安全)
│
├── kode/exception # 异常体系(错误码 / 链路追踪头)
│
├── kode/runtime # 协程运行时抽象
│
├── kode/facade # 服务门面(context-safe 协程安全解析,Kode 容器已接入)
│
├── kode/fibers # Fiber 协程调度
│ │
│ └── kode/parallel # 并行任务处理
│
├── kode/process # 进程管理和 Worker
│ │
│ └── kode/http-client # HTTP 客户端(统一到 PSR-7 抽象)
│
└── kode/queue # 后台任务队列(QueueMiddleware 响应后统一派发)
版本历史
- v3.4.13 - 性能:toCallable() callable 级缓存——消除 invoke() 每请求字符串解析 + 数组分配。v3.4.12 的
$instanceCache只省了new $class()实例化,但toCallable()每请求仍做str_contains+explode+ 新建[instance, method]数组。新增静态$callableCache:字符串处理器("Class@method"/"InvokableClass")按 handler 字符串缓存解析后的 callable,数组[class, method]按"class::method"键缓存——后续invoke()/compileRoute()直接命中缓存,跳过全部字符串操作 +class_exists+ 数组分配。闭包不缓存(已是 callable,直接返回)。 - v3.4.12 - 性能:控制器实例 worker 级缓存 + Uri path-only 快路径。①
RouteRunner::resolveClass()新增静态$instanceCache:无状态控制器在 worker 生命周期内只实例化一次,后续请求(无论经compileRoute()还是invoke())直接复用缓存实例,跳过每请求Kode::service()查找 +new $class()分配——框架 lean 路径(RouteRunner::invoke())此前每请求重复 DI 解析,这是最大剩余收益点。②Psr7\Uri::parse()快路径:以/开头的 path-only URI(如/bench/json)直接设$this->path,跳过parse_url()+ 7 次数组访问 +filterScheme开销;带 query 的 path(/search?q=foo)拆分?后分别设 path/query,仍避免parse_url();仅含 scheme(://)或 protocol-relative(//host)时回落完整解析。消除ServerRequest构造时每请求一次parse_url()分配。 - v3.4.11 - 性能:热路径零分配 Response——消除 json 端点残余 −12%(不可变 Response 物化成本)。①
Response::json()/make()默认参数(200 + Content-Type: application/json)走预构建模板clone快路径,跳过每请求new self()→ 构造函数 →initializeHeaders()(含strtolowerheader 规范化循环)的对象分配开销;非默认参数回落完整构造。②MiddlewarePipeline::handle()出口对已为ResponseInterface的结果跳过Response::resolve()的match(true)分发(绝大多数请求命中——CallableHandler 返回 Response / JsonErrorHandler 短路)。③RouteRunner::compileRoute()静态路由(无参数)编译为不含getAttribute('_route_params')查找的闭包 + inlineinstanceof ResponseInterface检查。三项合计消除每请求 ~1 次match分发 + 1 次strtolower+ 1 次哈希查找 + 构造函数方法链。 - v3.4.10 - 性能:热路径 facade 预置跳过 + 无参路由 attribute 克隆消除。①
RouteRunner::handle()无参路由(生产/压测绝对多数)跳过withAttribute不可变克隆 + 数组写;404/405 分支补Request::setRequest()保持 facade 语义(_route在包内零消费方,_route_params对空参恒等于默认值[])。②MiddlewareDispatcher::isBare()判定「仅默认异常中间件」的最小栈。③App::handle()栈为 bare 时跳过Request::setRequest预置(由 RouteRunner 派发时写入,含 404/405),每请求省一次 facade 写(~700ns);strtoupper→strcasecmp免字符串拷贝。 - v3.4.7 - 性能:Swoole emit 直取字符串体 + 小体响应纯内存 Stream。§7.1
SwooleServerAdapter::emit对Kode\Http\Response实例直接调用getBodyString()取内部字符串体,跳过 PSR-7getBody()->getContents()的 Stream 分发(非 kode 响应 fallback 原路径);§7.2 新增Psr7\StringStream(纯内存StreamInterface实现,getContents()/__toString()直接返回持有的字符串,isWritable()/isSeekable()返回 false),Stream::create()对 ≤1MB(含空串)返回StringStream,超限回落php://temp保留大文件落盘能力。消除 ~1KB 响应体每请求fopen('php://temp')+ 两次整段拷贝(fwrite / stream_get_contents)的开销。详见CHANGELOG.md - v3.4.6 - 性能:Swoole / Workerman 适配器 Uri 懒构造。新增
Psr7\LazyUri(实现UriInterface,with*不可变语义 /__toStringRFC 3986 拼装;不调用 parse_url、构造期不做 clone),适配器convertToServerRequest由new Uri($path)->withQuery($query)改为一次new LazyUri($path, $query),直接持有已分解的 path + query 两件原始分量。微基准(N=200k):适配器 Uri 构造成本 0.268 µs → 0.128 µs/op(约 2.1×);配合 v3.4.5 的LazyServerRequest,服务端入口请求构建彻底无 parse_url / clone / 急切 header 规范化。契约不变:LazyUri仅在适配器 path+query 热路径承接Uri,FPM 生产路径仍用Uri;PSR-7 / ServerRequest / Router / Emitter / 中间件管道全部未动。详见CHANGELOG.md - v3.4.5 - 统一/性能:三个服务端入口全部走
LazyServerRequest。ServerRunner::createServerRequestFromGlobals()改为委托ServerRequestFactory::fromGlobals()(删除重复的、规范化有误的 header 提取逻辑,让 FPM 生产路径也吃热路径零 header 成本);SwooleServerAdapter/WorkermanServerAdapter的convertToServerRequest由new ServerRequest改为new LazyServerRequest;LazyServerRequest::resolveHeaders加固——构造期已传入 header(适配器来源)时不再回源$_SERVER覆盖,避免丢失预解析 header。详见CHANGELOG.md - v3.4.4 - 性能:热路径零 header 成本。新增
Psr7\Message\LazyServerRequest(继承ServerRequest,可变语义 / PSR-7 契约不变),ServerRequestFactory::fromGlobals()改为构建它并将 header 规范化延迟到首次getHeader*访问;路由(method + path)完全不触发 header 提取。hasHeader在未解析时走原始源判定、不强制规范化;Request::hasTraceHeaders改为扫server params的HTTP_*键(热路径零 header 成本)。微基准:fromGlobals在不读 header 时由 8.68 µs → 1.41 µs/req(约 6.2×)。详见CHANGELOG.md - v3.4.3 - 缺陷修复:getBody() 非破坏性。
ResponseTrait/RequestTrait的getBody()物化Stream时保留 rawBody(去掉销毁赋值),hasRawBody()在任意次getBody()后恒为真,使Emitter快速路径不被kode/process::toHttp11每请求的getBody()封死,getRawBody()直接返回原串、无二次物化;withBody()/body()仍正确清rawBody保持单一真相源。详见CHANGELOG.md - v3.4.2 - 健壮性/性能:链路追踪上下文同步守卫。
Request新增TRACE_HEADERS单一真相源常量,syncTraceContext经hasTraceHeaders()守卫——无任一来源头(X-Request-Id / X-Trace-Id / traceparent / X-Correlation-Id)时直接返回,单次仅 4 次hasHeader查找、零Context写入。对任意多次setRequest调用(App::handle / RouteRunner / Request::json 等)天然幂等,且协程/Fiber 安全;不改setRequest签名、不动任何调用点、不碰 PSR-7 契约。详见CHANGELOG.md - v3.4.1 - 性能:懒原始体(lazy raw-body)+ Emitter 快速路径。消息构造函数与
getBody()加宽为StreamInterface|string|null,传入string仅存rawBody、getBody()按需懒物化Stream(保持 PSR-7 契约 BC);Response::body()只存rawBody并新增hasRawBody()/getRawBody();Emitter::emit()对持有rawBody的响应直接echo原始字符串、跳过 Stream 往返;全部入口(ServerRequestFactory/App::listen/ServerRunner/Swoole/Workerman)改为传原始字符串,消除每请求string → Stream → string无效分配。详见CHANGELOG.md - v3.4.0 - 性能重构(落地框架侧三方案):B
MiddlewarePipeline预编译为闭包链、零逐请求分配(删除PipelineRunner);CRouteRunner按路由缓存已解析 handler + 路由级管道;A 请求/响应消息改为可变(with*原地修改并返回自身,仿 webman / hyperf),移除 PSR-7 不可变语义。详见CHANGELOG.md - v3.3.0 - 合并 Response 工厂与真实 PSR-7:
Kode\Http\Response现在直接继承Psr7\Message\Response,json()/error()/success()/fail()返回的就是真实 PSR-7 响应,中间件/处理器可return Response::json(...)而无需->send()(保留为向后兼容空操作);Cookie 走Set-Cookie头、链式辅助方法(cookie/withCors/withSecurity…)全部保留;MiddlewarePipeline出管道时经Response::resolve()归一化 - v3.2.0 - 接入最新版
kode/facade(^3.2) 与kode/queue(^2.2):Kode实现 PSR-11 容器并接入FacadeProxy(context-safe 协程安全服务解析),新增Support/ServiceFacade基础门面;新增Queue/Queue门面封装(按请求 Context 作用域收集、响应后统一派发、未配置优雅降级)与Integration/QueueMiddleware;所有 kode 依赖锁定到最新稳定版 - v3.1.0 - 全面接入最新版 kode 生态:
kode/context升到^3.1、kode/exception升到^3.0,并接入kode/fibers(^4.10)/kode/parallel(^1.18)/kode/process(^5.2);Integration中间件改用最新版并发/进程引擎(Fibers 门面优先,parallel/process 可用时接管)并保留优雅降级;Request将入站X-Request-Id/traceparent/X-Trace-Id写入kode/context3.x 链路追踪;JsonErrorHandlerMiddleware透传X-Trace-Id/X-Span-Id链路头;修复extension_loaded('fibers')误判导致 Fiber 任务不执行的问题 - v3.0.0 - PHP 8.3+ 最低支持;重写路由器(静态哈希 + 动态正则、区分 404/405、命名路由 URL 生成)、无状态可重入中间件管道;新增
Status/Method枚举、Emitter、BodyParser/RequestId/ResponseTime/Compression/SecurityHeaders 中间件;修复 PSR-7 大小写不敏感头查找告警 - v2.1.0 - 增强 App 应用构建器,支持路由参数提取
- v2.0.0 - 借鉴 ThinkPHP/Laravel/webman 重构 API
- v1.5.0 - 增强 Request 请求助手方法
- v1.4.0 - 新增 App、Request、Response 统一 API
- v1.3.0 - 适配 kode/exception ^2.0
- v1.0.0 - 初始版本,PSR-7/15/17 基础实现
License
Apache-2.0