Loading

php Hyperf框架的注解路由POST、PUT、DELETE、PATCH请求如何使用?

 ✅ 方式一:使用 #[AutoController](自动路由,支持 GET / POST)

适合简单场景,无需手动指定路由路径,Hyperf 会自动为每个 public 方法 生成路由,同时支持 GET POST

✅ 示例代码:

<?php
declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\AutoController;

#[AutoController(prefix: "user")]
class UserController
{
    // 自动映射为 POST /user/register 或 GET /user/register
    public function register(RequestInterface $request)
    {
        $name = $request->input('name', 'Guest');
        return [
            'message' => "User {$name} registered.",
        ];
    }
}

✅ 访问方式:

  • POST http://localhost:9501/user/register

  • GET http://localhost:9501/user/register

注意:使用 AutoController 时,所有 public 方法都会自动生成路由,并同时支持 GET 和 POST,无法限制为仅 POST

✅ 方式二:使用 #[Controller] + #[PostMapping](精确控制)

适合需要 精确控制请求方式、路径、中间件 等场景。

✅ 示例代码:

<?php
declare(strict_types=1);

namespace App\Controller;

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

#[Controller(prefix: "api")]
class UserController
{
    // 仅允许 POST 请求,路径为 /api/login
    #[PostMapping(path: "login")]
    public function login(RequestInterface $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');

        return [
            'message' => "User {$username} logged in.",
        ];
    }
}

 

✅ 访问方式:

  • POST http://localhost:9501/api/login

使用 PostMapping 时,仅 POST 请求有效GET 请求将返回 405 Method Not Allowed。

✅ 小结对比:

特性 #[AutoController] #[Controller] + #[PostMapping]
是否自动注册路由 ✅ 是 ❌ 否,需手动标注
是否支持 POST ✅ 支持(同时支持 GET) ✅ 支持(仅 POST)
是否支持路径自定义 ❌ 否(按方法名自动生成) ✅ 是(可自定义 path)
是否支持中间件 ❌ 否 ✅ 是
适用场景 快速开发、简单接口 正式项目、RESTful 接口

✅ 查看路由列表(调试利器):

在项目根目录执行:

php bin/hyperf.php describe:routes

 

可查看当前所有注册的路由及其请求方式、路径、处理器。

如需进一步支持 PUT、DELETE、PATCH 等请求方式,可使用:

  • #[PutMapping]

  • #[DeleteMapping]

  • #[PatchMapping]

这些注解与 #[PostMapping] 用法完全一致,仅请求方式不同。

posted @ 2025-09-26 11:46  Carvers  阅读(23)  评论(0)    收藏  举报