update docs

This commit is contained in:
crazywhalecc
2020-12-25 16:53:44 +08:00
parent 747ecf28ea
commit 44979c670f
4 changed files with 155 additions and 2 deletions

View File

@@ -1,3 +1,125 @@
# 路由注解事件
TODO师傅莫催快肝完了
炸毛框架提供了一个简易但是高效易用的 HTTP 路由注解,你可以使用路由功能来开发任何 Web 应用微服务、API 接口、中间件等。
!!! quote "开发提示"
本章节涉及的路由和控制器概念可能和其他传统框架有一些出入,而且炸毛框架非绝对根据 PSR 标准进行开发,目的是使用上一些常见的东西尽可能地灵活和不罗嗦。
## 控制器和路由
Controller 和 Route 为路由注解事件的核心注解事件,其中 Controller 的注解事件为 `@Controller`Route 的注解事件为 `@RequestMapping`
### Controller()
#### 属性
| 类型 | 值 |
| ---------- | ------------------------------- |
| 名称 | `@Controller` |
| 触发前提 | 当路由 url 匹配到时进入触发 |
| 命名空间 | `ZM\Annotation\Http\Controller` |
| 适用位置 | 类 |
| 返回值处理 | 对类注解修饰,无返回值 |
#### 参数
| 参数名称 | 参数范围 | 用途 | 默认 |
| -------- | -------------- | ------------ | ---- |
| prefix | `string`,必需 | 控制器的 url | 空 |
### RequestMapping()
#### 属性
| 类型 | 值 |
| ---------- | ----------------------------------------------------------- |
| 名称 | `@RequestMapping` |
| 触发前提 | 当路由 url 匹配到时进入触发 |
| 命名空间 | `ZM\Annotation\Http\RequestMapping` |
| 适用位置 | 方法 |
| 返回值处理 | 返回类型是 `string` 时,自动调用 HTTP 响应并返回 200 状态码 |
#### 参数
| 参数名称 | 参数范围 | 用途 | 默认 |
| -------------- | ----------------------------------------------------------- | -------------------------- | ------------------------------------------ |
| route | `string`,必需 | 控制器的 url | 空 |
| name | `string` | 路由的名称 | 空 |
| request_method | `array`,限定 `RequestMethod::GET` 等常量 | 限制激活路由的 HTTP 方法 | `[RequestMethod::GET,RequestMethod::POST]` |
| params | `array`,当路由中含有如 `{id}` 类似的动态路由时,会动态改变 | 动态参数的路由参数值的绑定 | `[]` |
#### 函数调用参数
- `$param`:如果路由中存在变量(动态路由),则会把动态路由所匹配的参数放入 `$param` 数组中。
```php
/**
* @RequestMapping(route="/test/{ass}")
*/
public function testName($param) {
return "Your name is ".($param["ass"] ?? "unknown");
}
```
### 路由示例
=== "代码"
```php
<?php
namespace Module\Example;
use ZM\Annotation\Http\Controller;
use ZM\Annotation\Http\RequestMapping;
/**
* @Controller("/api")
*/
class Hello {
/**
* @RequestMapping("/index")
*/
public function index(){
ctx()->getResponse()->end("This is API index page"); // 使用上下文获取响应对象
}
/**
* @RequestMapping("/ping")
*/
public function ping(){
return "pong"; // 直接返回字符串
}
}
```
=== "效果"
!!! example "效果描述"
当访问浏览器的 `http://localhost:20001/api/index` 时,浏览器会返回 `This is API index page`,当访问 `/api/ping` 的 url 时,浏览器会返回 `pong`。
```
/ -> 无任何路由
/api/index -> Hello->index
/api/ping -> Hello->ping
```
!!! tip "提示"
当 `@Controller` 为 `/` 的时候,效果和不写是一样的,`@RequestMapping` 为 `/` 或 `/index/inside` 等多级路由也是可以的。
### 绑定参数
在 `@RequestMapping` 中,不仅可以写静态的路由地址,也可以写绑定的参数。例如:`@RequestMapping(route="/index/{name}")`,则访问 `/index/xxx` 的时候,你在函数方法内可以这样获取此参数:
```php
/**
* @RequestMapping("/index/{name}")
*/
public function index($arg) {
return "Your param 'name' is ".$arg["name"];
}
```
## 获取请求参数 GET / POST
炸毛框架支持获取外部 HTTP 请求进来的 GET 和 POST 请求,通过获取 HTTP 请求对象 [`Request`](/advanced/inside-class/) 即可。