|
| 1 | +# Route grouping |
| 2 | + |
| 3 | +In Dotkernel 6.0 with the help of the new [dot-router](https://docs.dotkernel.org/dot-router/v1/overview/) package, we have managed to implement a nicer way of creating routes. |
| 4 | +A lot of the times developers need to create sets of routes that have a similar format. As an example: |
| 5 | + |
| 6 | +```php |
| 7 | +$app->post('/product/create', CreateProductHandler::class, 'product:create'); |
| 8 | +$app->delete('/product/delete/{id}', DeleteProductHandler::class, 'product:delete'); |
| 9 | +$app->patch('/product/update/{id}', UpdateProductHandler::class, 'product:update'); |
| 10 | +$app->get('/product/view/{id}', GetProductHandler::class, 'product:view'); |
| 11 | +``` |
| 12 | + |
| 13 | +Along with the features from `mezzio/mezzio-fastroute`, the new `dot-router` package provides the ability to create route groups which are collections of routes that have the same base string for the path. |
| 14 | + |
| 15 | +Here we have an example from `src/User/src/RoutesDelegator.php` with the new grouping method: |
| 16 | + |
| 17 | +```php |
| 18 | +$routeCollector->group('/user/' . $uuid) |
| 19 | + ->delete('', DeleteUserResourceHandler::class, 'user::delete-user') |
| 20 | + ->get('', GetUserResourceHandler::class, 'user::view-user') |
| 21 | + ->patch('', PatchUserResourceHandler::class, 'user::update-user'); |
| 22 | +``` |
| 23 | + |
| 24 | +The advantages of this new implementation: |
| 25 | +- DRY - no need for repeating common route parts |
| 26 | +- encapsulation - similar routes are grouped in a single block of code (vs each route a separate statement) |
| 27 | +- easy path refactoring - modify all routes at once by changing only the prefix |
| 28 | +- easy copying/moving - copying/moving an entire group makes sure that you don't accidentally omit a route |
0 commit comments