[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();
}
~~~