Redirecting (short form)

Redirecting changed a lot over versions.

In Slim v2:

$app->redirect($app->urlFor('foo'));

In Slim v3:

$url = $this->router->pathFor('foo');
return $response->withStatus(302)->withHeader('Location', $url);

In Slim v4:

Set up the router once with

$app->addRoutingMiddleware();

Then:

$routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();
$url = $routeParser->urlFor('foo');
return $response->withStatus(302)->withHeader('Location', $url);

Is there anything shorter for v4 that I’d have missed?

If, to make things shorter and easier to read, I make a helper class to shorten the syntax, what is the recommended way to access the router then? e.g. make $app a global available to my Helper class? Pass $request to the Helper class?

Any tip on the topic is welcome.
Thanks.

Hi @fabswt Good question.

There is a set of PSR-7 object decorators providing useful convenience methods, such as Response::withRedirect($url, $status). But you still need the RouteParser to create a URL by a route name. So there is no real “shortcut” at all.

Hey Odan,

Thanks. I ended up doing it like this:

    /**
     * Redirect.
     *
     * Inspired by Slim's RouteParserInterface.
     *
     * @param string $destination URL or Route name
     * @param array  $data        Named argument replacement data
     * @param array  $queryParams Optional query string parameters
     *
     * @return string
     *
     * @throws RuntimeException         If named route does not exist
     * @throws InvalidArgumentException If required data not provided
     */
    public static function redirect($request, $response, string $destination, array $data = [], array $queryParams = []) {
        if (filter_var($destination, FILTER_VALIDATE_URL)) {
            $url = $destination;
                // WOULDDO(): add support for query parameters, if I need it.
        } else {
            $routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();
            $url = $routeParser->urlFor($destination, $data, $queryParams);
        }
        return $response->withStatus(302)->withHeader('Location', $url);
    }
1 Like

A post was split to a new topic: Inject PSR-7 object decorators to route in Slim 4