5、Hyperf 3 快速使用 - Hypref 3 请求处理

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 1857

时间: 2023-04-25 12:13:21

hi,我是温新,一名 PHPer

学习目标:掌握对请求的处理

获取请求对象

可以通过容器注入 Hyperf\HttpServer\Contract\RequestInterface 获得 对应的 Hyperf\HttpServer\Request,实际注入的对象为一个代理对象,代理的对象为每个请求的 PSR-7 请求对象(Request),也就意味着仅可在 onRequest 生命周期内可获得此对象。

两种注解获取参数

#[AutoController]

第一步:添加路由

# 路由
Router::get('/user/info/{id}', [\App\Controller\UserController::class, 'info']);

第二步:添加控制器方法

public function info(RequestInterface $request, int $id = 0)
{
    return $id;
}

对于 #[Controller] 注解,添加案例中形式的路由参数,需要通过 routes.php 定义路由。

#[Controller]

第一步:创建控制器

<?php
App\Controller\Demo\TestController.php
namespace App\Controller\Demo;

use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

#[Controller]
class TestController
{
    // 直接注解控制器中定义路由参数
    #[RequestMapping('info/{id}', 'get')]
    public function info(RequestInterface $request, int $id)
    {
        // 可以通过 route() 获取参数
        $id1 = $request->route('id');

        return $id1;
    }
}

第二步:访问路由

$curl http://localhost:9501/demo/test/info/11234
11234

获取请求参数

获取所有参数

以数组的形式获取所有数据。

# 接收数据
$all = $request->all();

获取指定输入值

通过 input(string $key, $default = null)inputs(array $keys, $default = null): array 获取 一个多个 任意形式的输入值:

// 获取单个值

// 存在则返回,不存在则返回 null
$name = $request->input('name');
// 存在则返回,不存在则返回默认值 Hyperf
$name = $request->input('name', 'Hyperf');

如果传输表单数据中包含「数组」形式的数据,那么可以使用「点」语法来获取数组:

// 获取数组形式的参数
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');

从查询字符串获取输入

使用 input, inputs 方法可以从整个请求中获取输入数据(包括 Query 参数),而 query(?string $key = null, $default = null) 方法可以只从查询字符串中获取输入数据:

// 存在则返回,不存在则返回 null
$name = $request->query('name');
// 存在则返回,不存在则返回默认值 Hyperf
$name = $request->query('name', 'Hyperf');
// 不传递参数则以关联数组的形式返回所有 Query 参数
$name = $request->query();

获取 json 数据

请求的 body 数据格式为 json,需要在请求头加上 content-type 的值 application/json,然后就可以正常获取参数了。

// 存在则返回,不存在则返回 null
$name = $request->input('user.name');
// 存在则返回,不存在则返回默认值 Hyperf
$name = $request->input('user.name', 'Hyperf');
// 以数组形式返回所有 Json 数据
$name = $request->all();

确定是否存在输入值

要判断请求是否存在某个值,可以使用 has($keys) 方法。

Cookies

从请求头中获取 Cookies

使用 getCookieParams() 方法从请求中获取所有的 Cookies,结果会返回一个关联数组。

$cookies = $request->getCookieParams();

如果希望获取某一个 Cookie 值,可通过 cookie(string $key, $default = null) 方法来获取对应的值:

// 存在则返回,不存在则返回 null
$name = $request->cookie('name');
// 存在则返回,不存在则返回默认值 Hyperf
$name = $request->cookie('name', 'Hyperf');

本篇文章学习了对相关请求参数的处理。

请登录后再评论