8

100 days of code - Day 2

 3 years ago
source link: https://dev.to/hananekacemi/100-days-of-code-day-2-219o
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
100 days of code

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 modeExit 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 modeExit 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 modeExit fullscreen mode

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK