基本路由
您将中定义应用程序的所有路由在routes/web.php文件中。最基本的Lumen路由仅接受URI和Closure
<?php$router->get('foo', function () {return 'Hello World';});$router->post('foo', function () {//});
可用的路由器方法
路由器允许您注册响应任何HTTP动词的路由:
<?php$router->get($uri, $callback);$router->post($uri, $callback);$router->put($uri, $callback);$router->patch($uri, $callback);$router->delete($uri, $callback);$router->options($uri, $callback);
路由参数
必要参数
当然,有时您需要捕获路由内的URI段。例如,您可能需要从URL中捕获用户的ID。您可以通过定义路由参数来做到这一点:
<?php$router->get('user/{id}', function ($id) {return 'User '.$id;});
您可以根据自己的路由定义任意数量的路由参数:
<?php$router->get('posts/{postId}/comments/{commentId}', function ($postId, $commentId) {//});
路由参数始终包含在“花括号”中。执行路由时,参数将传递到您的路由的Closure。
注意:路由参数不能包含
-字符。请改用下划线(_)。
可选参数
您可以通过将部分路由URI定义括在[...]中来定义可选的路由参数。因此,例如,/foo[bar]将同时匹配/foo和/foobar。可选参数仅在URI的末尾位置受支持。换句话说,您不能在路径定义的中间放置可选参数:
<?php$router->get('user[/{name}]', function ($name = null) {return $name;});
正则表达式约束
您可以通过在路由定义中定义一个正则表达式来限制路由参数的格式:
<?php$router->get('user/{name:[A-Za-z]+}', function ($name) {//});
命名路由
使用命名路由,可以方便地生成URL或特定路由的重定向。as定义路由时,可以使用数组键为路由指定名称:
<?php$router->get('profile', ['as' => 'profile', function () {//}]);
您还可以为控制器操作指定路由名称:
<?php$router->get('profile', ['as' => 'profile', 'uses' => 'UserController@showProfile']);
生成URL到命名路由
为给定的路由分配名称后,可以在生成URL或通过全局route函数重定向时使用该路由的名称:
<?php// Generating URLs...$url = route('profile');// Generating Redirects...return redirect()->route('profile');
如果命名路由定义了参数,则可以将参数作为第二个参数传递给route函数。给定的参数将自动以正确的位置插入URL:
<?php$router->get('user/{id}/profile', ['as' => 'profile', function ($id) {//}]);$url = route('profile', ['id' => 1]);
路由组
路由组使您可以在大量路由之间共享路由属性,例如中间件或名称空间,而无需在每个单独的路由上定义那些属性。共享属性以数组格式指定为$router->group方法的第一个参数。
要了解有关路由组的更多信息,我们将逐步介绍该功能的几个常见用例。
中间件
要将中间件分配给组内的所有路由,可以使用middleware组属性数组中的键。中间件将按照您定义此数组的顺序执行:
<?php$router->group(['middleware' => 'auth'], function () use ($router) {$router->get('/', function () {// Uses Auth Middleware});$router->get('user/profile', function () {// Uses Auth Middleware});});
命名空间
路由组的另一个常见用例是将相同的PHP名称空间分配给一组控制器。您可以namespace在组属性数组中使用参数来为组中的所有控制器指定名称空间:
<?php$router->group(['namespace' => 'Admin'], function() use ($router){// Using The "App\Http\Controllers\Admin" Namespace...$router->group(['namespace' => 'User'], function() use ($router) {// Using The "App\Http\Controllers\Admin\User" Namespace...});});
路由前缀
该prefix组属性可被用于前缀与给定URI的组中的每个路由。例如,您可能想在组内的所有路由URI前面加上admin:
<?php$router->group(['prefix' => 'admin'], function () use ($router) {$router->get('users', function () {// Matches The "/admin/users" URL});});
您还可以使用prefix参数为分组的路由指定通用参数:
<?php$router->group(['prefix' => 'accounts/{accountId}'], function () use ($router) {$router->get('detail', function ($accountId) {// Matches The "/accounts/{accountId}/detail" URL});});
