3.4 响应

在 Hyperf 里可通过 Hyperf\HttpServer\Contract\ResponseInterface 接口类来注入 Response 代理对象对响应进行处理,默认返回 Hyperf\HttpServer\Response 对象,该对象可直接调用所有 Psr\Http\Message\ResponseInterface 的方法。

注意 PSR-7 标准为 响应(Response) 进行了 immutable 机制 的设计,所有以 with 开头的方法的返回值都是一个新对象,不会修改原对象的值

1. 引入请求的对象

<?php
namespace App\Controller;

abstract class AbstractController
{
    /**
     * @Inject
     * @var \Hyperf\HttpServer\Contract\ResponseInterface
     */
    protected $response;
}

2. 返回参数

<?php

# 返回json数据
  $this->response->json(['key' => 'value']);

# 返回xml数据
  $this->response->xml(['key' => 'value']);

// 文件下载
  $this->response->download('/opt/flie.csv', 'filename.csv');

// Cookie设置
  $this->response->withCookie(new Cookie('key', 'value'))->withContent('hello world')
文档更新时间: 2021-09-26 16:00   作者:赵豪