DEV Community

Hanane Kacemi
Hanane Kacemi

Posted on

2 1

100 days of code - Day 2

Today, we'll go through the Symfony Routing component, which allows to set up routing in PHP applications.

We can add this component to the project with this command : composer require symfony/routing

the main Classes of this component that we will see are : RouteCollection, Route, UrlMatcher,RequestContext

Let's create an instance of RouteCollection, we will use it to define all routes of our application :

$routes = new RouteCollection();

To add a route to this collection, we use the function "add" we give it a name and we create an instance of Route which is defined by a route pattern and an array of default values for route attributes, below are 2 examples :

$routes->add('greeting', new Route('/hello/{name}', ['name' => 'world']));
$routes->add('goodbye', new Route('/bye'));
Enter fullscreen mode Exit fullscreen mode

in order to match the current URL with one of those in our Collection, we need to use UrlMatcher :

$matcher = new UrlMatcher($routes, $context);

$context is an object of RequestContext, it holds the current request context informations :

$context = new RequestContext();
$context->fromRequest (Request::createFromGlobals());
Enter fullscreen mode Exit fullscreen mode

now We have everything we need to match any route against the predefined routes that we have ($routes object). To do that we use match method of $matcher object

$matcher->match($context->getPathInfo());

If the route is found, we get the custom attributes associated with that route. Otherwise, the ResourceNotFoundException exception is thrown if there's no route associated with the current URI.

Here is the output of $parameters if we access to /hello/joe :

var_dump($parameters)

 /* Result:
[
    'name' => 'joe',
    '_route' => 'hello',
];
*/
Enter fullscreen mode Exit fullscreen mode

That's all for today, see you next time.
Have a nice day

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️