DEV Community

loading...

100 days of code - Day 2

hananekacemi profile image hanane kacemi ・1 min read

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

Discussion (0)

pic
Editor guide