| 3 |
liveuser |
1 |
Routing Component
|
|
|
2 |
=================
|
|
|
3 |
|
|
|
4 |
The Routing component maps an HTTP request to a set of configuration variables.
|
|
|
5 |
|
|
|
6 |
Getting Started
|
|
|
7 |
---------------
|
|
|
8 |
|
|
|
9 |
```
|
|
|
10 |
$ composer require symfony/routing
|
|
|
11 |
```
|
|
|
12 |
|
|
|
13 |
```php
|
|
|
14 |
use App\Controller\BlogController;
|
|
|
15 |
use Symfony\Component\Routing\Generator\UrlGenerator;
|
|
|
16 |
use Symfony\Component\Routing\Matcher\UrlMatcher;
|
|
|
17 |
use Symfony\Component\Routing\RequestContext;
|
|
|
18 |
use Symfony\Component\Routing\Route;
|
|
|
19 |
use Symfony\Component\Routing\RouteCollection;
|
|
|
20 |
|
|
|
21 |
$route = new Route('/blog/{slug}', ['_controller' => BlogController::class]);
|
|
|
22 |
$routes = new RouteCollection();
|
|
|
23 |
$routes->add('blog_show', $route);
|
|
|
24 |
|
|
|
25 |
$context = new RequestContext();
|
|
|
26 |
|
|
|
27 |
// Routing can match routes with incoming requests
|
|
|
28 |
$matcher = new UrlMatcher($routes, $context);
|
|
|
29 |
$parameters = $matcher->match('/blog/lorem-ipsum');
|
|
|
30 |
// $parameters = [
|
|
|
31 |
// '_controller' => 'App\Controller\BlogController',
|
|
|
32 |
// 'slug' => 'lorem-ipsum',
|
|
|
33 |
// '_route' => 'blog_show'
|
|
|
34 |
// ]
|
|
|
35 |
|
|
|
36 |
// Routing can also generate URLs for a given route
|
|
|
37 |
$generator = new UrlGenerator($routes, $context);
|
|
|
38 |
$url = $generator->generate('blog_show', [
|
|
|
39 |
'slug' => 'my-blog-post',
|
|
|
40 |
]);
|
|
|
41 |
// $url = '/blog/my-blog-post'
|
|
|
42 |
```
|
|
|
43 |
|
|
|
44 |
Resources
|
|
|
45 |
---------
|
|
|
46 |
|
|
|
47 |
* [Documentation](https://symfony.com/doc/current/routing.html)
|
|
|
48 |
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
|
|
|
49 |
* [Report issues](https://github.com/symfony/symfony/issues) and
|
|
|
50 |
[send Pull Requests](https://github.com/symfony/symfony/pulls)
|
|
|
51 |
in the [main Symfony repository](https://github.com/symfony/symfony)
|