6、Hyperf 3 快速使用 - Hypref 3 响应

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 398

时间: 2023-04-25 12:15:17

hi,我是温新,一名 PHPer

学习目标:掌握对响应的处理

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

返回 json

// App\Controller\UserController.php

use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;

public function show(RequestInterface $request, ResponseInterface $response):Psr7ResponseInterface
{
    $data = [
        'name' => '王美丽'
    ];

    return $response->json($data);
}

同理,可以返回 xml 和 raw。

重定向

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

redirect 方法:

参数 类型 默认值 备注
toUrl string 如果参数不存在 http://https:// 则根据当前服务的 Host 自动拼接对应的 URL,且根据 $schema 参数拼接协议
status int 302 响应状态码
schema string http $toUrl 不存在 http://https:// 时生效,仅可传递 httphttps
// App\Controller\UserController.php
public function info(RequestInterface $request, int $id = 0)
{
    return $id . ' 来了';
}

public function show(RequestInterface $request, ResponseInterface $response):Psr7ResponseInterface
{
    return $response->redirect('/user/info/10');
}

关于视图,留到下篇文章学习。

请登录后再评论