响应
Hyperf\HttpServer\Contract\ResponseInterface
提供了 json($data)
方法用于快速返回 Json
格式,并设置 Content-Type
为 application/json
,$data
接受一个数组或为一个实现了 Hyperf\Utils\Contracts\Arrayable
接口的对象。
返回 Xml 格式
Hyperf\HttpServer\Contract\ResponseInterface
提供了 xml($data)
方法用于快速返回 XML
格式,并设置 Content-Type
为 application/xml
,$data
接受一个数组或为一个实现了 Hyperf\Utils\Contracts\Xmlable
接口的对象。
<?php
namespace App\Controller;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
class IndexController
public function xml(ResponseInterface $response): Psr7ResponseInterface
{
$data = [
'key' => 'value'
];
return $response->xml($data);
}
}
返回 Raw 格式
请参考 视图 部分文档
重定向
Hyperf\HttpServer\Contract\ResponseInterface
提供了 redirect(string $toUrl, int $status = 302, string $schema = 'http')
返回一个已设置重定向状态的 Psr7ResponseInterface
对象。
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');
}
Cookie 设置
分块传输编码 Chunk
文件下载
Hyperf\HttpServer\Contract\ResponseInterface
提供了 download(string $file, string $name = '')
返回一个已设置下载文件状态的 Psr7ResponseInterface
对象。如果请求中带有 if-match
或 if-none-match
的请求头,Hyperf 也会根据协议标准与 ETag
进行比较,如果一致则会返回一个 304
状态码的响应。
download
方法:
参数 | 类型 | 默认值 | 备注 |
---|---|---|---|
file | string | 无 | 要返回下载文件的绝对路径,同通过 BASE_PATH 常量来定位到项目的根目录 |
name | string | 无 | 客户端下载文件的文件名,为空则会使用下载文件的原名 |