## Route placeholders路線占位符
Each routing method described above accepts a URL pattern that is matched against the current HTTP request URI. Route patterns may use named placeholders to dynamically match HTTP request URI segments.
> 上面描述的每個路由方法都接受一個與當前HTTP請求URI匹配的URL模式。路由模式可以使用命名占位符來動態匹配HTTP請求URI段。
### Format格式化
A route pattern placeholder starts with a `{` , followed by the placeholder name, ending with a `}` . This is an example placeholder named `name` :
> 路由模式占位符以`{`開頭,后跟占位符名稱,以`}`結尾。這是一個名為`name`的占位符示例:
~~~php
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
$name = $args['name'];
echo "Hello, $name";
});
~~~
### Optional segments可選部分
To make a section optional, simply wrap in square brackets:
> 要使一個部分可選,只需用方括號括起來:
~~~php
$app->get('/users[/{id}]', function ($request, $response, $args) {
// responds to both `/users` and `/users/123`
// but not to `/users/`
});
~~~
Multiple optional parameters are supported by nesting:
> 嵌套支持多個可選參數:
~~~php
$app->get('/news[/{year}[/{month}]]', function ($request, $response, $args) {
// reponds to `/news`, `/news/2016` and `/news/2016/03`
});
~~~
For “Unlimited” optional parameters, you can do this:
對于`傳入`可選參數,你可以這樣做:
~~~php
$app->get('/news[/{params:.*}]', function ($request, $response, $args) {
// $params is an array of all the optional segments
$params = explode('/', $args['params']);
});
~~~
In this example, a URI of`/news/2016/03/20`would result in the`$params`array containing three elements:`['2016', '03', '20']`.
> 在本例中,URI`/news/2016/03/20`將導致`$params`數組包含三個元素:` ['2016','03','20']`
### Regular expression matching正則表達式匹配
By default the placeholders are written inside`{}`and can accept any values. However, placeholders can also require the HTTP request URI to match a particular regular expression. If the current HTTP request URI does not match a placeholder regular expression, the route is not invoked. This is an example placeholder named`id`that requires one or more digits.
> 默認情況下占位符寫在`{}`里面,可以接受任何值。但是,占位符也可能需要HTTP請求URI來匹配特定的正則表達式。如果當前HTTP請求URI不匹配占位符正則表達式,則不會調用路由。這是一個名為`id`的占位符示例,它需要一個或多個數字。
~~~php
$app->get('/users/{id:[0-9]+}', function ($request, $response, $args) {
// Find user identified by $args['id']
});
~~~
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir