Symfony Routing Component

repository·8.2·Indexed 27 days ago

https://github.com/symfony/routing

A component that maps HTTP requests to configuration variables, providing functionality for URL matching to determine the appropriate controller and URL generation for creating application links.

Tokens
615
Snippets
2
Records
2
Agent score
43%

What's inside symfony/routing

  1. Match URLs to routes and generate URLs

    8.2

    The Routing component allows you to match incoming request paths to specific routes and extract parameters, as well as generate URLs for existing routes.

    To use it, you need to define a Route, add it to a RouteCollection, and provide a RequestContext. You then use UrlMatcher for matching and UrlGenerator for generation.

    use App\Controller\BlogController;
    use Symfony\Component\Routing\Generator\UrlGenerator;
    use Symfony\Component\Routing\Matcher\UrlMatcher;
    use Symfony\Component\Routing\RequestContext;
    use Symfony\Component\Routing\Route;
    use Symfony\Component\Routing\RouteCollection;
    
    $route = new Route('/blog/{slug}', ['_controller' => BlogController::class]);
    $routes = new RouteCollection();
    $routes->add('blog_show', $route);
    
    $context = new RequestContext();
    
    // Routing can match routes with incoming requests
    $matcher = new UrlMatcher($routes, $context);
    $parameters = $matcher->match('/blog/lorem-ipsum');
    // $parameters = [
    //     '_controller' => 'App\Controller\BlogController',
    //     'slug' => 'lorem-ipsum',
    //     '_route' => 'blog_show'
    // ]
    
    // Routing can also generate URLs for a given route
    $generator = new UrlGenerator($routes, $context);
    $url = $generator->generate('blog_show', [
        'slug' => 'my-blog-post',
    ]);
    // $url = '/blog/my-blog-post'