对于 请求(Request) 与 响应(Response),Hyperf 提供了 Hyperf\HttpServer\Contract\RequestInterface 和 Hyperf\HttpServer\Contract\ResponseInterface 方便您获取入参和返回数据。
请求 :http://domain.com/foo/bar?baz=1
$request->path(); // 将会返回 foo/bar
$request->url(); // 没有查询参数
$request->fullUrl(); // 带上查询参数
$request->getMethod(); // 获取请求方法
$request->all(); // 获取所有输入
// 获取所有参数
$this->request->all()
//获取指定输入值
$request->input('name'); // 存在则返回,不存在则返回 null
$request->input('name', 'Hyperf'); // 存在则返回,不存在则返回默认值 Hyperf
//如果传输表单数据中包含「数组」形式的数据,那么可以使用「点」语法来获取数组:
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');
// 获取url上的参数
$request->query('name', ''); // 存在则返回,不存在则返回默认值 Hyperf
// 获取 JSON 输入信息
如果请求的 Body 数据格式是 JSON,则只要 请求对象(Request) 的 Content-Type Header 值 正确设置为 application/json,
就可以通过 input(string $key, $default = null) 方法访问 JSON 数据,你甚至可以使用 「点」语法来读取 JSON 数组
$request->input('user.name', 'Hyperf'); // 存在则返回,不存在则返回默认值 Hyperf
$method = $request->getMethod();
if ($request->isMethod('post'))
{
// ...
} 响应
# 返回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')本文为崔凯原创文章,转载无需和我联系,但请注明来自冷暖自知一抹茶ckhttp://www.cksite.cn