3、Hyperf 3 快速使用 - Hypref 3 注解定义路由之 #[AutoController]

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 387

时间: 2023-04-25 12:07:49

hi,我是温新,一名 PHPer

学习目标:掌握 #[AutoController] 注解的形式使用路由

本篇文章的重点不是注解,但还是得提一提。当觉得不好理解的时候不要放弃,看看文档,自己动手试一试,说不定自然就通透了。

关于注解路由的形式,文档中已经了有详细的说明,现在动手试试吧。

对于注解路由,hyperf 提供了非常便利的注解路由功能,可以在任意类上通过定义#[Controller]#[AutoController] 注解来完成一个路由的定义。

通过注解定义路由

#[AutoController] 注解

1、使用 #[AutoController] 注解路由时,该注解只会对类中的所有 public 修饰的类方法进行注解,并提供 GETPOST 两种请求方式;

2、使用 #[AutoController] 注解时需 use Hyperf\HttpServer\Annotation\AutoController; 命名空间;

驼峰命名的控制器,会自动转化为蛇形路由,以下为控制器与实际路由的对应关系示例:

控制器 注解 & 访问路由 访问路由
MyDataController @AutoController() /my_data/index
MydataController @AutoController() /mydata/index
MyDataController @AutoController(prefix="/data") /data/index

第一步:创建控制器与方法

<?php
// App\Controller\UserController.php
    
namespace App\Controller;

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

#[AutoController]
class UserController
{
    // Hyperf 会自动为此方法生成一个 /user/index 的路由,允许通过 GET 或 POST 方式请求
    public function index(RequestInterface $request)
    {
        // 从请求中获得 id 参数
        $id = $request->input('id', 1);
        return (string)$id;
    }
}

第二步:路由访问

# 方式一
curl http://localhost:9501/user?id=120
curl http://localhost:9501/user

# 方式二
curl http://localhost:9501/user/index?id=100
curl http://localhost:9501/user/index

使用注解路由后,会自动带上前缀,如使用的是 UserController,那么前缀就是 user

使用了注解路由后,就不需要在 routes.php 路由文件中定义路由了。

需要注意的是,一旦使用该注解路由,protectedprivate 将无法直接访问该路由,只能在类内部中使用。

第三步:测试使用私有路由

改造控制器

// App\Controller\UserController.php
public function index(RequestInterface $request)
{
    $id = $request->input('id', 1);
    return (string)$id .  '' . $this->getUserinfo();
}

protected function getUserinfo()
{
    return '王美丽';
}

第四步:访问路由

$curl http://localhost:9501/user
1王美丽
$curl $curl http://localhost:9501/user/getUserinfo
Not Found
请登录后再评论