php Hyperf框架的注解路由get请求如何使用?
·
方案一:在 #[AutoController] 中使用请求对象【访问方式:http://127.0.0.1:9501/v1/user/index?id=6】
你也可以通过注入 Request 对象来获取参数,这种方式对查询参数和路径参数都适用( 但前提是路由本身要支持,而 #[AutoController] 默认不会生成带路径参数的路由,#[Controller] 才支持带路径参数的路由 ):
<?php
namespace App\Controller;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface; // 引入请求接口
#[AutoController(prefix: "/v1/user")]
class IndexController
{
public function index(RequestInterface $request)
{
$id = $request->input('id'); // 从请求中获取 id 参数
return $id;
}
}
方案二:改用 #[Controller] 和 #[GetMapping] 注解(推荐)
1. 通过注入 Request 对象来获取请求的参数【访问方式:http://127.0.0.1:9501/v1/user/index?id=6】
<?php
namespace App\Controller;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Contract\RequestInterface; // 引入请求接口
#[Controller(prefix: "/v1/user")]
class IndexController
{
#[GetMapping(path: "index")]//可以自定义路径
public function index(RequestInterface $request)
{
$id = $request->input('id');
return $id;
}
}
2. 通过定义路径参数来获取请求的参数【访问方式:http://127.0.0.1:9501/v1/user/index/6】
<?php
namespace App\Controller;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
#[Controller(prefix: "/v1/user")]
class IndexController
{
#[GetMapping(path: "index/{id}")] // 明确定义路径参数,可以自定义路径
public function index(int $id) // 直接从路径中获取参数
{
return $id;
}
}
注意:
1. #[Controller] 和 #[GetMapping] 注解中的 #[GetMapping] 请求路径可以自定义:
比如:#[GetMapping( path: "index/{id}") ] 可以自定为:#[GetMapping( path: "test/{id}") ]。
2. #[GetMapping] 前面不能加 / ,但是 #[Controller] 的路径前面必须加 / 。
更多推荐




所有评论(0)