Hyperf Response 响应处理完全指南:从 JSON/XML 到流式下载与 EventStream
Hyperf Response 响应处理完全指南:从 JSON/XML 到流式下载与 EventStream
本文围绕 Hyperf 协程框架的 HTTP 响应处理能力展开,讲解如何通过 Hyperf\HttpServer\Contract\ResponseInterface 代理对象灵活构造并返回 JSON、XML、Raw、HTML、View、重定向、Cookie、文件下载与分块流式(chunked)等各类响应。读完本文,你将掌握 Hyperf 中响应对象的注入方式、PSR-7 不可变机制的注意事项,以及每个响应方法背后的源码实现细节,可直接应用于控制器开发与微服务接口设计中。
响应对象的注入与 PSR-7 不可变机制
在 Hyperf 中,控制器方法可以通过依赖注入直接获得响应代理对象,声明类型为 Hyperf\HttpServer\Contract\ResponseInterface。默认情况下,容器会注入 Hyperf\HttpServer\Response 实例,该实例同时实现了 Psr\Http\Message\ResponseInterface 与框架自身的 ResponseInterface,因此你可以直接调用 PSR-7 标准中的 withStatus()、withHeader()、withBody() 等方法。
注意:PSR-7 标准为 Response 设计了不可变(immutable)机制,所有以
with开头的方法(如withHeader、withStatus)返回的都是新的对象,不会修改原始对象的值。因此在使用时务必接收并返回方法调用的结果,否则修改不会生效。
从源码角度看,Response 类通过 call() 方法将 with* 系列调用转发给底层响应对象,并返回 new static(...) 包装的新实例(见 Response.php);同时该类使用了 Macroable trait,支持通过宏(macro)扩展自定义方法,也支持把不存在的方法通过 __call 代理到底层 PSR-7 响应对象(见 Response.php),这让响应对象既完整又灵活。
返回 JSON 格式
ResponseInterface 提供 json($data) 方法,将数据序列化为 JSON 并设置 Content-Type: application/json。$data 可以是数组,也可以是实现了 Hyperf\Contract\Arrayable 接口的对象(该接口要求实现 toArray(): array,定义见 Arrayable.php)。
<?php
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
class IndexController
{
public function json(ResponseInterface $response): Psr7ResponseInterface
{
$data = [
'key' => 'value'
];
return $response->json($data);
}
}
源码实现要点(见 Response.php):
- 通过
toJson()内部调用Hyperf\Codec\Json::encode()完成序列化,若编码过程抛出异常,会包装为Hyperf\HttpServer\Exception\Http\EncodingException抛出(见 Response.php); - 实际返回的
Content-Type为application/json; charset=utf-8,响应体使用SwooleStream包装,避免字符串拷贝,贴合协程场景的高性能要求。
返回 XML 格式
xml($data, string $root = 'root', string $charset = 'utf-8') 将数据转为 XML 并设置 Content-Type: application/xml。$data 可以是数组或实现了 Hyperf\Contract\Xmlable 接口的对象(Xmlable 继承自 Stringable,见 Xmlable.php)。
<?php
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
class IndexController
{
public function xml(ResponseInterface $response): Psr7ResponseInterface
{
$data = [
'key' => 'value'
];
return $response->xml($data);
}
}
源码实现要点(见 Response.php):
- 内部调用
Hyperf\Codec\Xml::toXml($data, null, $root)完成数组到 XML 的转换,$root参数用于指定根节点名称,默认值为root; - 输出头为
application/xml; charset=utf-8,charset参数可按需调整。
返回 Raw 纯文本格式
raw($data, string $charset = 'utf-8') 将数据以纯文本形式返回并设置 Content-Type: text/plain。$data 可以是字符串,也可以是任何实现了 __toString() 的对象(即 Stringable)。原文档中提到的 plain/text 为笔误,实际源码设置的头部为 text/plain(见 Response.php)。
<?php
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
class IndexController
{
public function raw(ResponseInterface $response): Psr7ResponseInterface
{
return $response->raw('Hello Hyperf.');
}
}
此外,ResponseInterface 还提供了 html(string $html, string $charset = 'utf-8') 方法,用于返回 Content-Type: text/html 的 HTML 响应(见 ResponseInterface.php),适合直接输出页面片段或模板渲染结果。
返回 View 视图
返回视图需要借助 Hyperf 的视图组件(hyperf/view),具体渲染流程与模板引擎(Blade、Smarty、Twig、Plates、ThinkTemplate)的配置请参阅 View 文档。在控制器中通常是先渲染视图得到 HTML 字符串,再通过 html() 或 raw() 返回,也可以结合模板引擎在 Task Worker 中完成渲染后输出。相关配置(如 view_path、cache_path)同样在 View 文档中有详细说明。
重定向 Redirect
redirect(string $toUrl, int $status = 302, string $schema = 'http') 返回带重定向状态的 Psr7ResponseInterface 对象。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| toUrl | string | 无 | 若参数不含 http:// 或 https://,将基于当前服务 Host 自动拼接 URL,协议由 $schema 决定 |
| status | int | 302 | 响应状态码 |
| schema | string | http | 仅当 toUrl 不含 http:// 或 https:// 时生效,只能传 http 或 https |
<?php
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
class IndexController
{
public function redirect(ResponseInterface $response): Psr7ResponseInterface
{
// redirect() 返回的是 Psr\Http\Message\ResponseInterface 对象,需要再次 return 出去
return $response->redirect('/anotherUrl');
}
}
源码实现要点(见 Response.php):
- 若
toUrl以http://或https://开头则原样使用; - 否则从当前请求的
RequestContext中取出 URI 的 authority(即 Host 与端口部分),拼接为schema://host/path;toUrl未以/开头时会自动补全前导/; - 最终通过
withStatus($status)->withAddedHeader('Location', $toUrl)生成 30x 重定向响应。
设置 Cookie
通过 withCookie(Cookie $cookie) 可以给响应附加 Cookie。Cookie 类位于 Hyperf\HttpMessage\Cookie 命名空间,构造参数丰富,支持过期时间、路径、域名、安全标志、HttpOnly、SameSite 等(见 Cookie.php)。
<?php
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
use Hyperf\HttpMessage\Cookie\Cookie;
class IndexController
{
public function cookie(ResponseInterface $response): Psr7ResponseInterface
{
$cookie = new Cookie('key', 'value');
return $response->withCookie($cookie)->withContent('Hello Hyperf.');
}
}
使用要点:
new Cookie(string $name, string $value = '', $expire = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httpOnly = true, ...),expire支持DateTimeInterface、时间戳或可被strtotime()解析的字符串(见 Cookie.php);- Cookie 名称不能为空且不能包含
= , ; 空格 制表符 回车 换行等非法字符,否则会抛出InvalidArgumentException(见 Cookie.php); SameSite提供了lax、strict、none三个预定义常量(见 Cookie.php)。
Chunked 分块传输与 EventStream
write(string $data) 用于向浏览器逐步推送响应数据,并设置 Transfer-Encoding: chunked。$data 可以是字符串或实现了 __toString() 的对象。底层实现中,只有当底层响应对象实现了 Hyperf\HttpMessage\Server\Chunk\Chunkable 接口时才会真正执行分块写入,否则返回 false(见 Response.php)。
配合 Hyperf\Engine\Http\EventStream 可以轻松实现 Server-Sent Events(SSE)推送:
<?php
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Swoole\Coroutine;
use Hyperf\Engine\Http\EventStream;
class IndexController
{
public function index(ResponseInterface $response)
{
$response
->withStatus(200)
->withHeader('X-Event-Mode', 'Enabled') // ⭐ Custom Header
->withHeader('X-Stream-Time', '5s');
$streamer = new EventStream($this->response->getConnection(), $response);
$startTime = time();
$totalSteps = 5;
$streamer->write("data: --- 🚀 EventStream started (total {$totalSteps} steps) ---\n\n");
for ($i = 1; $i <= $totalSteps; ++$i) {
Coroutine::sleep(1);
$elapsed = time() - $startTime;
$message = "data: 【{$i} second】data block sent. Time elapsed: {$elapsed} seconds\n\n";
$streamer->write($message);
}
$streamer->write("data: --- ✅ EventStream ended ---\n\n");
$streamer->end();
return 'Hello Hyperf';
}
}
注意:调用
write开始分块传输后,若再用return返回数据,该数据不会显示。在上面的例子中,Hello Hyperf不会出现,浏览器只会收到data: 【{$i} second】data block sent. Time elapsed: {$elapsed} seconds\n\n格式的流式数据。
分块传输非常适合大文件导出、实时日志推送、AI 流式对话等长耗时场景,配合协程 Coroutine::sleep() 可以在不阻塞 Worker 的前提下按节奏推送数据。
文件下载 Download
download(string $file, string $name = '') 返回带下载语义的 Psr7ResponseInterface 响应。若请求头包含 if-match 或 if-none-match,Hyperf 会按协议规范与 ETag 比对;若匹配则直接返回状态码 304 的响应。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| file | string | 无 | 待下载文件的绝对路径,建议使用 BASE_PATH 常量定位项目根目录 |
| name | string | 无 | 客户端下载时显示的文件名,留空则使用文件原名 |
<?php
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
class IndexController
{
public function index(ResponseInterface $response): Psr7ResponseInterface
{
return $response->download(BASE_PATH . '/public/file.csv', 'filename.csv');
}
}
源码实现要点(见 Response.php):
- 文件不可读时会抛出
Hyperf\HttpServer\Exception\Http\FileException; ETag默认通过对文件内容做md5_file生成(弱校验模式则基于lastModified与filesize生成W/"..."格式),见 Response.php;- 若请求携带的
if-match或if-none-match中包含该ETag,则返回304 Not Modified,客户端可复用本地缓存,有效节省带宽; - 正常下载时会依次设置
content-description: File Transfer、content-type(优先通过MimeTypeExtensionGuesser根据扩展名推断,否则回退为application/octet-stream)、content-disposition: attachment; filename=...; filename*=UTF-8''...、content-transfer-encoding: binary、pragma: public与etag头; - 响应体使用
SwooleFileStream流式读取文件,避免将整个文件载入内存,适合大文件下载。
小结
Hyperf 通过统一的 ResponseInterface 代理对象,将 PSR-7 标准能力与框架级便捷方法(json、xml、raw、html、redirect、withCookie、write、download)合为一体,同时保持响应对象的不可变语义与协程友好的流式处理。理解这些方法的底层实现(见 http-server 源码 与 契约定义),有助于你在微服务接口、文件服务、实时推送等场景中写出正确且高性能的响应代码。