Hyperf 响应(Response)实战指南:从 JSON 输出到文件下载的完整用法与源码解析
Hyperf 响应(Response)实战指南:从 JSON 输出到文件下载的完整用法与源码解析
本指南以 Hyperf 的 Hyperf\HttpServer\Contract\ResponseInterface 为核心,系统讲解在控制器中如何快速返回 JSON、XML、纯文本、视图、重定向、Cookie 与文件下载响应。读完本文,你将掌握 Hyperf 响应对象的获取方式、各类快捷方法的参数与默认值、PSR-7 不可变性带来的注意事项,以及底层 Response 类的真实实现逻辑,可直接用于日常接口开发。
获取响应对象
在 Hyperf 中,响应对象不需要手动 new,而是通过依赖注入(DI)容器直接获取。你只需在控制器构造方法或方法参数中注入 Hyperf\HttpServer\Contract\ResponseInterface 接口:
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
class IndexController
{
public function index(ResponseInterface $response): Psr7ResponseInterface
{
// ...
}
}
默认情况下,DI 容器会返回 Hyperf\HttpServer\Response 对象(Response.php)。该类同时实现了 PSR-7 的 Psr\Http\Message\ResponseInterface 与 Hyperf 自定义的 Hyperf\HttpServer\Contract\ResponseInterface,因此你可以直接调用 PSR-7 规范中的全部方法(如 withHeader、withStatus、withBody 等)。
注意 PSR-7 不可变性:PSR-7 标准的响应对象是不可变对象(immutable object)。所有以
with开头的方法返回值都是一个新的对象,不会修改原对象的值。因此请务必把方法调用链的最终结果return出去,而不是在中间步骤上继续操作旧对象。
源码里的代理机制
从源码看,Response 类内部通过 getResponse() 从 Hyperf\Context\ResponseContext 中取出当前协程上下文里的真实 PSR-7 响应对象(Response.php),并将 withXxx 系列方法委托给该对象执行,然后以 new static(...) 包装返回新实例(Response.php)。这意味着你在任何位置调用 withCookie、withStatus 等方法,操作的都是"当前请求上下文"对应的响应,天然具备协程隔离性。
返回 JSON
通过 ResponseInterface::json($data) 可以快速返回 JSON 格式内容,响应对象的 Content-Type 会被自动设置为 application/json。$data 支持三种类型:
- 普通数组(array)
- 实现了
Hyperf\Contract\Arrayable接口的对象(提供toArray(): array方法,见 Arrayable.php) - 实现了
Hyperf\Contract\Jsonable接口的对象(提供toJson(int $options = 0): string方法,见 Jsonable.php)
<?php
declare(strict_types=1);
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);
}
}
从源码看,json() 的实现分为两步(Response.php):
- 调用
toJson()通过Hyperf\Codec\Json::encode()对数据进行编码(Response.php),编码失败会抛出Hyperf\HttpServer\Exception\Http\EncodingException; - 为响应对象添加
content-type: application/json; charset=utf-8头,并将编码结果包装进Hyperf\HttpMessage\Stream\SwooleStream流作为响应体。
测试用例 ResponseTest.php 验证了 json() 对数组、布尔值、浮点数、嵌套数组的编码结果,也验证了 json((object) ['id' => 1]) 这类对象输入可直接输出 {"id":1}。
返回 XML
通过 ResponseInterface::xml($data) 可以快速返回 XML 格式内容,Content-Type 自动设置为 application/xml。$data 支持数组或实现了 Hyperf\Contract\Xmlable 接口的对象(该接口继承自 Stringable,见 Xmlable.php)。
<?php
declare(strict_types=1);
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);
}
}
xml() 的方法签名比文档中的基础示例更丰富(Response.php):
public function xml($data, string $root = 'root', string $charset = 'utf-8'): PsrResponseInterface
$root:XML 根节点名称,默认为root;$charset:编码字符集,默认utf-8,最终生成的Content-Type为application/xml; charset={$charset}。
底层通过 Hyperf\Codec\Xml::toXml() 完成数组到 XML 的转换(Response.php)。测试 ResponseTest.php 给出了完整的输出示例:字符串、整数、浮点数、布尔值、嵌套数组都会被转换为对应 XML 节点,实现了 Arrayable 与 Xmlable 的对象同样适用。
返回原始内容
通过 ResponseInterface::raw($data) 可以快速返回原始字符串内容,Content-Type 自动设置为 text/plain。$data 可以是字符串,也可以是任何实现了 __toString() 方法的对象(Stringable)。
<?php
declare(strict_types=1);
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.');
}
}
源码实现中,raw() 会把 $data 强制转换为字符串((string) $data)后写入 SwooleStream,并设置 content-type: text/plain; charset=utf-8(Response.php)。
补充:html() 方法
ResponseInterface 还提供了 html(string $html, string $charset = 'utf-8') 方法用于返回 HTML 片段,Content-Type 为 text/html; charset={$charset}(Response.php)。测试 ResponseTest.php 验证了默认 UTF-8 与指定 GBK 字符集两种场景下响应头的变化。对于完整页面渲染,建议配合视图引擎使用(见下文)。
返回视图
如需返回视图模板渲染结果,请参考 视图(View)指南(中文版见 View)。response 本身不直接承担模板渲染职责,视图功能由 hyperf/view 组件配合 hyperf/view-engine 提供。
重定向
ResponseInterface::redirect(string $toUrl, int $status = 302, string $schema = 'http') 用于返回一个已设置好重定向状态与 Location 头的 PSR-7 响应对象。
参数说明:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| toUrl | string | 无 | 重定向目标地址。若不以 http:// 或 https:// 开头,会根据当前服务器的 Host 自动拼接完整 URL,拼接协议由 $schema 决定 |
| status | int | 302 | 响应状态码 |
| schema | string | http | 仅在 $toUrl 不以 http:// / https:// 开头时生效,只允许 http 或 https |
<?php
declare(strict_types=1);
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');
}
}
从源码看,重定向的 URL 拼接逻辑如下(Response.php):
- 若
$toUrl以http://或https://开头,直接作为Location值; - 否则从
RequestContext::get()->getUri()->getAuthority()取出当前请求的 Host(含端口),组合为{$schema}://{$host}{$toUrl};若$toUrl不以/开头,会自动补一个/。
测试 ResponseTest.php 验证了四类场景:传入完整 https://、http:// 地址时原样返回;传入 /index 或 index 时均拼出 http://127.0.0.1:9501/index,且状态码均为 302。
设置 Cookie
通过 ResponseInterface::withCookie(Cookie $cookie) 可以为响应附加 Cookie。Cookie 类位于 Hyperf\HttpMessage\Cookie\Cookie(Cookie.php),其完整构造参数如下:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| name | string | 必填 | Cookie 名称,不能为空,且不能包含 = , ; 空格 \t \r \n \v \f 等非法字符 |
| value | string | '' |
Cookie 值 |
| expire | DateTimeInterface/int/string | 0 |
过期时间,支持时间对象、Unix 时间戳或可被 strtotime 解析的字符串;0 表示会话级 Cookie |
| path | string | / |
Cookie 生效路径,为空时回退为 / |
| domain | string | '' |
Cookie 生效域名 |
| secure | bool | false |
是否仅通过 HTTPS 传输 |
| httpOnly | bool | true |
是否仅允许 HTTP 协议访问(默认开启,防止 JS 读取) |
| raw | bool | false |
是否不对 Cookie 值做 URL 编码 |
| sameSite | ?string | null |
跨站请求策略,支持 lax / strict / none 三个常量(Cookie::SAMESITE_LAX 等) |
| partitioned | bool | false |
是否启用 CHIPS(Partitioned Cookie) |
示例:
<?php
declare(strict_types=1);
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.');
}
}
注意 withCookie() 返回的是 Hyperf\HttpServer\Contract\ResponseInterface(即仍可继续链式调用 Hyperf 扩展方法),最终需要 return 一个 PSR-7 响应对象给框架。
Cookie 是如何发送出去的
在响应真正写给客户端时,Hyperf\HttpServer\ResponseEmitter::emit() 会遍历响应对象的 Cookie 列表,调用 Swoole 的 rawcookie() 写入(ResponseEmitter.php):非 raw 模式的 Cookie 值会先经过 rawurlencode,空值会被替换为字符串 deleted(用于清除 Cookie)。测试 ResponseTest.php 验证了多个 Cookie 的写入、Cleared 空值 Cookie 的处理,以及响应头 X-Token 的设置流程。
文件下载
ResponseInterface::download(string $file, string $name = '') 用于返回一个已配置好文件下载响应头的 PSR-7 响应对象。
参数说明:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| file | string | 无 | 要下载文件的绝对路径,可使用 BASE_PATH 常量定位项目根目录 |
| name | string | '' |
客户端下载时显示的文件名,为空则使用文件原名 |
<?php
declare(strict_types=1);
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');
}
}
从源码看,download() 的处理流程相当完整(Response.php):
- 文件校验:将
$file包装为SplFileInfo,若文件不可读则抛出Hyperf\HttpServer\Exception\Http\FileException; - ETag 生成:默认通过
md5_file()计算文件内容摘要作为强 ETag;也支持弱 ETag 模式(基于修改时间与文件大小的W/"%x-%x"格式,见 Response.php); - MIME 类型推断:若容器中存在
Hyperf\Support\MimeTypeExtensionGuesser,则根据文件扩展名猜测 MIME 类型,否则回退为application/octet-stream; - 条件请求处理:若请求头携带
if-match或if-none-match,Hyperf 会按协议标准与计算出的 ETag 比较,命中时直接返回304 Not Modified状态码的响应(Response.php); - 下载响应头:未命中缓存时,设置
content-description: File Transfer、content-type、content-disposition: attachment; filename=...; filename*=UTF-8''...(后者为 URL 编码的文件名)、content-transfer-encoding: binary、pragma: public、etag等头,并将响应体设置为Hyperf\HttpMessage\Stream\SwooleFileStream。
大文件如何零拷贝发送
下载场景下,响应体是 SwooleFileStream(实现了 Hyperf\HttpMessage\Stream\FileInterface)。在 ResponseEmitter.php 中,当检测到响应体实现 FileInterface 时,会直接调用 Swoole 的 $connection->sendfile() 发送文件,而非把整个文件读入内存,从而以零拷贝方式高效传输大文件。
流式输出:Gzip 压缩与 Chunk 分块
ResponseInterface 还声明了 write(string $data): bool 方法(ResponseInterface.php),用于实现分块传输(Chunked Transfer Encoding)。从源码看(Response.php),write() 会判断底层响应对象是否实现了 Hyperf\HttpMessage\Server\Chunk\Chunkable 接口,若是则把数据写入当前分块并返回 true,否则返回 false:
public function write(string $data): bool
{
$response = $this->getResponse();
if ($response instanceof Chunkable) {
return $response->write($data);
}
return false;
}
这意味着分块能力取决于当前 Swoole 环境提供的响应对象是否支持 Chunkable,可结合服务端配置开启。Gzip 压缩则通常在 Swoole HTTP 服务层(http_compression 相关配置)统一处理,Response 对象本身不做内容压缩,避免与应用层输出叠加造成双重压缩。
响应发送链路小结
一次完整的响应生命周期如下:
- 控制器方法通过 DI 注入
ResponseInterface,调用json()/xml()/raw()/download()等快捷方法,或直接使用 PSR-7 的with*方法构造响应对象; - 所有修改均作用于当前协程上下文(
ResponseContext)中的 PSR-7 响应对象,并返回新实例; - 框架的
CoreMiddleware收到控制器返回值后,交由Hyperf\HttpServer\ResponseEmitter::emit()将响应头、Cookie、状态码写入 Swoole 连接并发送内容(ResponseEmitter.php); - 若响应体是
SwooleFileStream,则走sendfile()零拷贝通道;其余情况通过end()发送。
理解这条链路后,你就能明白为什么"必须把 with* 或快捷方法的返回值 return 出去"——因为中间产生的新对象才是最终需要发送的响应。
结语
本文从响应对象的获取入手,完整覆盖了 Hyperf 中最常用的响应输出方式:JSON、XML、原始内容、视图、重定向、Cookie 与文件下载,并结合 src/http-server 与 src/http-message 的源码剖析了每个方法背后的真实实现。在实际项目中,你可以依据接口场景灵活组合这些能力:API 优先使用 json(),需要缓存协商时使用 download() 配合 ETag,涉及会话态时使用 withCookie()。相关源码与测试可直接在 src/http-server/src/Response.php 与 src/http-server/tests/ResponseTest.php 中查阅。