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.

a helper class to shorten the syntax, what is the recommended way to access the router

I asked myself the same question just some days ago. Global variables are always bad.
A helper class sounds good e.g.

To create a redirect for the given route name:

$response = ResponseHelper::create()->redirectFor($request, $response, 'foo');

Retriving the url for the given route name:

$url = ResponseHelper::create()->urlFor($request, 'foo');

To create a redirect for the given url:

$response = ResponseHelper::create()->redirect($response, $url);

and so on…

PS: I’m working on a new slim-helper package.

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