3.1路由

路由所处的目录

cd config/routes.php

定义路由的方式:在路由文件里为某个控制器注册路由

- 接收方法:
    - get:获取数据
    - post:新增数据
    - put:更新该数据的所有内容
    - patch:更新该数据的局部内容
    - delete:删除该数据
- 参数定义:(定义了参数后url上的路径必须以 / 结尾,否则不能访问)
    - {id}:必选
    - [{id}]:选填
- 组的定义:addGroup,第一个参数是路有前缀,必须以 / 开头
- 中间件:定义在路由方法中的第三个参数中,(addRoute是第四个参数),key为middleware,值为数组多个中间件的类名
<?php
use Hyperf\HttpServer\Router\Router;

# 第一种方式: http://127.0.0.1:9501/test/1
    Router::get('/test', 'App\Controller\IndexController@test');

# 第二种方式: http://127.0.0.1:9501/test/
    Router::addRoute(['GET'], '/test', 'App\Controller\IndexController@test');

# 第三种方式:匿名函数 http://127.0.0.1:9501/test2
Router::get('/test2', function () {
    return 'hello world';
});

-------------------------------------------------------

# 组的方式定义路由 http://127.0.0.1:9501/api/test/1
Router::addGroup('/api', function () {
    Router::get('/test/{id}', 'App\Controller\IndexController@test');
});

# 加入中间件
Router::get('/test/{id}', 'App\Controller\IndexController@test', [
    "middleware" => [ApiSignMiddleware::class]
]);

定义路由的方式:通过注解的方式

  • @AutoControler:根据方法名来直接访问,只允许get和post请求
<?php
namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;

/**
 * 定义路由的前缀为test
 * @AutoController()
 */
class TestController extends AbstractController
{
    public function list()
    {
        return __METHOD__;
    }
}

访问的方式:
- GET:http://127.0.0.1:9501/test/list
- POST:http://127.0.0.1:9501/test/list

@Controller 为满足更细致的路由定义需求而存在,使用 @Controller 注解用于表明当前类为一个 Controller 类,同时需配合 @RequestMapping 注解来对请求方法和请求路径进行更详细的定义。
我们也提供了多种快速便捷的 Mapping 注解,如 @GetMapping@PostMapping@PutMapping@PatchMapping@DeleteMapping 5 种便捷的注解用于表明允许不同的请求方法。

使用 @Controller 注解时需 use Hyperf\HttpServer\Annotation\Controller; 命名空间;
使用 @RequestMapping 注解时需 use Hyperf\HttpServer\Annotation\RequestMapping; 命名空间;
使用 @GetMapping 注解时需 use Hyperf\HttpServer\Annotation\GetMapping; 命名空间;
使用 @PostMapping 注解时需 use Hyperf\HttpServer\Annotation\PostMapping; 命名空间;
使用 @PutMapping 注解时需 use Hyperf\HttpServer\Annotation\PutMapping; 命名空间;
使用 @PatchMapping 注解时需 use Hyperf\HttpServer\Annotation\PatchMapping; 命名空间;
使用 @DeleteMapping 注解时需 use Hyperf\HttpServer\Annotation\DeleteMapping; 命名空间;

<?php
declare(strict_types=1);

namespace App\Controller;

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

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

推荐写法

  1. 不使用注解书写路由,为了方便以文件的形式进行管理,例如查找与版本控制管理等
  2. 书写方式推荐:Router::get('/test', 'App\Controller\IndexController@test');
  3. 以字母开头,下划线衔接。例如: get_user_info/{id}
文档更新时间: 2021-10-08 13:33   作者:赵豪