在 Hyperf 里可通过 HyperfHttpServerContractResponseInterface
接口类来注入 Response
代理对象对响应进行处理,默认返回 HyperfHttpServerResponse
对象,该对象可直接调用所有 PsrHttpMessageResponseInterface
的方法。
注意 PSR-7 标准为 响应(Response) 进行了 immutable 机制 的设计,所有以 with 开头的方法的返回值都是一个新对象,不会修改原对象的值
<?php
namespace AppController;
abstract class AbstractController
{
/**
* @Inject
* @var HyperfHttpServerContractResponseInterface
*/
protected $response;
}
PHP
Copy
<?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')
PHP
Copy