cd config/routes.php
Bash
Copy
- 接收方法:
- get:获取数据
- post:新增数据
- put:更新该数据的所有内容
- patch:更新该数据的局部内容
- delete:删除该数据
- 参数定义:(定义了参数后url上的路径必须以 / 结尾,否则不能访问)
- {id}:必选
- [{id}]:选填
- 组的定义:addGroup,第一个参数是路有前缀,必须以 / 开头
- 中间件:定义在路由方法中的第三个参数中,(addRoute是第四个参数),key为middleware,值为数组多个中间件的类名
<?php
use HyperfHttpServerRouterRouter;
# 第一种方式: http://127.0.0.1:9501/test/1
Router::get('/test', 'AppControllerIndexController@test');
# 第二种方式: http://127.0.0.1:9501/test/
Router::addRoute(['GET'], '/test', 'AppControllerIndexController@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}', 'AppControllerIndexController@test');
});
# 加入中间件
Router::get('/test/{id}', 'AppControllerIndexController@test', [
"middleware" => [ApiSignMiddleware::class]
]);
PHP
Copy
<?php
namespace AppController;
use HyperfHttpServerAnnotationAutoController;
/**
* 定义路由的前缀为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
PHP
Copy
@Controlle
code>@Controller 为满足更细致的路由定义需求而存在,使用 code>@Controller 注解用于表明当前类为一个 Controller 类,同时需配合 code>@RequestMapping 注解来对请求方法和请求路径进行更详细的定义。
我们也提供了多种快速便捷的 Mapping 注解,如 code>@GetMapping、code>@PostMapping、code>@PutMapping、code>@PatchMapping、code>@DeleteMapping 5 种便捷的注解用于表明允许不同的请求方法。
使用 @Controller 注解时需 use HyperfHttpServerAnnotationController; 命名空间; 使用 @RequestMapping 注解时需 use HyperfHttpServerAnnotationRequestMapping; 命名空间; 使用 @GetMapping 注解时需 use HyperfHttpServerAnnotationGetMapping; 命名空间; 使用 @PostMapping 注解时需 use HyperfHttpServerAnnotationPostMapping; 命名空间; 使用 @PutMapping 注解时需 use HyperfHttpServerAnnotationPutMapping; 命名空间; 使用 @PatchMapping 注解时需 use HyperfHttpServerAnnotationPatchMapping; 命名空间; 使用 @DeleteMapping 注解时需 use HyperfHttpServerAnnotationDeleteMapping; 命名空间;
PHP
Copy
推荐写法
不使用注解书写路由,为了方便以文件的形式进行管理,例如查找与版本控制管理等
书写方式推荐:Router::get('/test', 'AppControllerIndexController@test');
以字母开头,下划线衔接。例如: get_user_info/{id}