92 lines
3.2 KiB
Markdown
92 lines
3.2 KiB
Markdown
# 3.7 路由注册
|
||
|
||
:::tip 概述
|
||
路由定义在 `route/app.php` 中,按模块分组注册。所有需认证的接口统一绑定四个中间件。
|
||
:::
|
||
|
||
## 路由文件位置
|
||
|
||
```text
|
||
route/app.php
|
||
```
|
||
|
||
## Example 模块路由(来自项目实际代码)
|
||
|
||
```php
|
||
// route/app.php 第 370~383 行
|
||
|
||
// ----------------------------------------------------------
|
||
// 自动生成 - example
|
||
// ----------------------------------------------------------
|
||
Route::group('example', function () {
|
||
Route::get('page', 'ExampleController/page'); // 分页列表
|
||
Route::get('list', 'ExampleController/list'); // 全量列表
|
||
Route::get('detail/:id', 'ExampleController/detail'); // 详情(:id 为路径参数)
|
||
Route::post('add', 'ExampleController/add'); // 新增
|
||
Route::put('update', 'ExampleController/update'); // 修改
|
||
Route::delete('delete/:id', 'ExampleController/delete'); // 删除
|
||
Route::delete('batchDelete', 'ExampleController/batchDelete'); // 批量删除
|
||
Route::post('import', 'ExampleController/import'); // 导入
|
||
Route::get('export', 'ExampleController/export'); // 导出
|
||
});
|
||
```
|
||
|
||
## 路由格式说明
|
||
|
||
```php
|
||
Route::HTTP方法('路径', '控制器/方法');
|
||
```
|
||
|
||
| HTTP 方法 | 用途 | 路径格式 | 示例 |
|
||
|-----------|------|----------|------|
|
||
| GET | 查询 | `/module/page`、`/module/detail/:id` | `GET /api/example/page` |
|
||
| POST | 新增/导入 | `/module/add`、`/module/import` | `POST /api/example/add` |
|
||
| PUT | 修改 | `/module/update` | `PUT /api/example/update` |
|
||
| DELETE | 删除 | `/module/delete/:id`、`/module/batchDelete` | `DELETE /api/example/delete/1` |
|
||
|
||
## 标准路由模板
|
||
|
||
每个业务模块通常包含以下路由:
|
||
|
||
```php
|
||
Route::group('模块名', function () {
|
||
Route::get('page', 'XxxController/page'); // 分页列表
|
||
Route::get('list', 'XxxController/list'); // 全量列表(可选)
|
||
Route::get('detail/:id', 'XxxController/detail'); // 详情
|
||
Route::post('add', 'XxxController/add'); // 新增
|
||
Route::put('update', 'XxxController/update'); // 修改
|
||
Route::delete('delete/:id', 'XxxController/delete'); // 删除
|
||
Route::delete('batchDelete', 'XxxController/batchDelete'); // 批量删除
|
||
Route::post('import', 'XxxController/import'); // 导入(可选)
|
||
Route::get('export', 'XxxController/export'); // 导出(可选)
|
||
});
|
||
```
|
||
|
||
:::tip 路由命名规范
|
||
- 路径使用小写英文(如 `example`、`user`)
|
||
- 详情/删除使用 `:id` 参数(如 `detail/:id`)
|
||
- 批量删除使用 `batchDelete` 路径
|
||
:::
|
||
|
||
## 中间件绑定
|
||
|
||
所有需认证的接口在 `route/app.php` 末尾统一绑定中间件:
|
||
|
||
```php
|
||
})->middleware([
|
||
\app\middleware\AuthMiddleware::class, // JWT认证 + 权限校验
|
||
\app\middleware\TenantMiddleware::class, // 租户上下文注入
|
||
\app\middleware\DemoMiddleware::class, // 演示环境拦截
|
||
\app\middleware\LogMiddleware::class, // 操作日志记录
|
||
]);
|
||
```
|
||
|
||
## 验证路由注册
|
||
|
||
```bash
|
||
# 查看所有已注册路由
|
||
php think route:list
|
||
|
||
# 测试路由是否正确
|
||
curl http://localhost:8000/api/example/page -H "Authorization: Bearer <token>"
|
||
``` |