nikic / FastRoute

Fast request router for PHP
Other
5.13k stars 445 forks source link

Suggested add the route name #234

Closed andy236726493 closed 10 months ago

andy236726493 commented 3 years ago

for example:

$r->addRoute('GET', '/test', 'handler')->name("test“);

burzum commented 3 years ago

I've added this feature to my complete refactor https://github.com/burzum/FastRoute/tree/fastroute-ng/src and I might make it into this PR or whatever @lcobucci and me are going to do within the next few days or weeks. https://github.com/nikic/FastRoute/pull/223

And it is not that simple. Internally it can generate a route for more than one HTTP method. So you would have to get by name AND method. You're invited to figure out a better solution. :)

    public function addRoute($httpMethod, string $route, $handler, ?string $name = null): void
    {
        $route = $this->currentGroupPrefix . $route;
        $routingData = $this->routeParser->parse($route);

        foreach ((array) $httpMethod as $method) {
            foreach ($routingData as $routeData) {
                $route = $this->dataGenerator->addRoute($method, $routeData, $handler, $name);
                $name = $route->name();

                if ($name !== null && isset($this->namedRoutes[$method])) {
                    $this->namedRoutes[$method][$name] = $route;
                }
            }
        }
    }

I think this could be refactored and it should be refactored, so that the data generator uses route objects instead of generating them. But this is not a quick refactor.

kimjohans commented 3 years ago

That ->name('..') or better ->setName('webIndex') is a very big point for me.

I am working on a very big project and naming the routes is quite important, because nobody will write down the URLs inside views and other redirects. With ->setName() i would be able to change the URL without searching and changing all references inside my code ... and forget one of course.

lcobucci commented 3 years ago

Named routes are definitely on my list... I'm quite busy with paid work but the plan is to finish the work on #244 and then go back to applying the work that has been done by @burzum

kktsvetkov commented 2 years ago

@kimjohans have you considered https://github.com/thephpleague/route ? It is an upgrade on top of FastRoute and they do have named routes:

https://route.thephpleague.com/5.x/routes/#named-routes

Named routes helps when you want to retrieve a Route by a human friendly label.

<?php declare(strict_types=1);

$router = new League\Route\Router;
$request = new Request; // Psr/Http/Message/ServerRequestInterface

$router->group('/admin', function (\League\Route\RouteGroup $route) {
    $route->map('GET', '/acme/route1', 'AcmeController::actionOne')->setName('actionOne');
    $route->map('GET', '/acme/route2', 'AcmeController::actionTwo')->setName('actionTwo');
});

$route = $router->getNamedRoute('actionOne');
$route->getPath(); // "/admin/acme/route1"