ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 配置方式 > 配置文件:config/routes.php ~~~ use Hyperf\\HttpServer\\Router\\Router; // 下面三种方式的任意一种都可以达到同样的效果 Router::get('/hello-hyperf', 'App\\Controller\\IndexController::hello'); Router::post('/hello-hyperf', 'App\\Controller\\IndexController@hello'); Router::get('/hello-hyperf', [App\\Controller\\IndexController::class, 'hello']); ~~~ ## 注解方式 > phpstorm中需要安装 PHP Annotations 插件,便于语法提示 ### @AutoController 注解 > `@AutoController`会为所有`public`方法并提供`GET`和`POST`两种请求 ~~~ declare(strict_types=1); 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; } } ~~~ ### @Controller 注解 > `@Controller`为更细致的路由定义需求,需同时配合`@RequestMapping` 或 (`@GetMapping`、`@PostMapping`) ~~~ 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() */ public function index() { return 'test'; } /** * @RequestMapping(path="user", methods="get,post") */ public function user(RequestInterface $request) { // 从请求中获得 id 参数 $id = $request->input('id', 1); return (string)$id; } } ~~~ ## 路由参数定制 > 配置文件:config/routes.php ~~~ Router::get('/user/{id}', 'App\\Controller\\UserController::info'); ~~~ > 修改/app/Controller/UserController.php ~~~ public function info(int $id) { $user = User::find($id); return $user->toArray(); } ~~~