响应

    Hyperf\HttpServer\Contract\ResponseInterface 提供了 json($data) 方法用于快速返回 Json 格式,并设置 Content-Typeapplication/json$data 接受一个数组或为一个实现了 Hyperf\Utils\Contracts\Arrayable 接口的对象。

    返回 Xml 格式

    Hyperf\HttpServer\Contract\ResponseInterface 提供了 xml($data) 方法用于快速返回 XML 格式,并设置 Content-Typeapplication/xml$data 接受一个数组或为一个实现了 Hyperf\Utils\Contracts\Xmlable 接口的对象。

    1. <?php
    2. namespace App\Controller;
    3. use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
    4. class IndexController
    5. public function xml(ResponseInterface $response): Psr7ResponseInterface
    6. {
    7. $data = [
    8. 'key' => 'value'
    9. ];
    10. return $response->xml($data);
    11. }
    12. }

    返回 Raw 格式

    请参考 视图 部分文档

    重定向

    Hyperf\HttpServer\Contract\ResponseInterface 提供了 redirect(string $toUrl, int $status = 302, string $schema = 'http') 返回一个已设置重定向状态的 Psr7ResponseInterface 对象。

    1. namespace App\Controller;
    2. use Hyperf\HttpServer\Contract\ResponseInterface;
    3. use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
    4. class IndexController
    5. {
    6. public function redirect(ResponseInterface $response): Psr7ResponseInterface
    7. {
    8. // redirect() 方法返回的是一个 Psr\Http\Message\ResponseInterface 对象,需再 return 回去
    9. return $response->redirect('/anotherUrl');
    10. }

    分块传输编码 Chunk

    文件下载

    Hyperf\HttpServer\Contract\ResponseInterface 提供了 download(string $file, string $name = '') 返回一个已设置下载文件状态的 Psr7ResponseInterface 对象。如果请求中带有 if-matchif-none-match 的请求头,Hyperf 也会根据协议标准与 ETag 进行比较,如果一致则会返回一个 304 状态码的响应。

    download 方法:

    参数 类型 默认值 备注
    file string 要返回下载文件的绝对路径,同通过 BASE_PATH 常量来定位到项目的根目录
    name string 客户端下载文件的文件名,为空则会使用下载文件的原名