100 days of code - Day 2
Hanane Kacemi
Posted on May 2, 2021
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'));
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());
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',
];
*/
That's all for today, see you next time.
Have a nice day
Posted on May 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.