Using response->withRedirect() with route Name (rather than URL)

As I’m adding functionality to my project, I’ve stumbled across this issue. Response::withRedirect() is defined as follows:

public function withRedirect($url, $status = 302)
    return $this->withStatus($status)->withHeader('Location', (string)$url);

This is all fine and well, but I’d much prefer to use the redirect with route name as it’s target rather than a URL. Is there any way this can be achieved?

BTW, this is done from Controller code, so the variable available to me in this context are:

public function pageEdit (Request $request, Response $response, $args)

so I don’t quite see how to get resolve a route name to a URL based on the available parameters.

Once again, thanks for any insights.

I use something like this to redirect to a route named home:

$uri = $request->getUri()->withPath($this->router->pathFor('home')); return $response->withRedirect((string)$uri);

Note: I’m passing the router ($this->router) to the controller’s constructor.

Thank you, that’s exactly what I was looking for.

Thanks TheLobos…:slight_smile:

We should thank @tflight, he’s been most helpful in getting me (and probably others) up to speed.

1 Like

Hi @tflight,

Can you explain how to pass the router to the controller’s constructor?


@xpico, you can where the controller is defined in the container here, note the router on line 41.:

And the router is then added to the controller’s constructor here:

1 Like

Thank @tflight for the answer.

I have another question. Why pass 3 arguments in new Bookshelf\BookController($c['view'], $c['router'], $c['flash']); and not all the container with $c like new Bookshelf\BookController($c); and then in the controller you can use what you want? Is performance or what?

Sorry, but I’m not an expert with PHP and with dependency container concept.

See this article, particularly the second to the last paragraph as well as the first comment and answer.

You could also search for articles about Service Locator VS Dependency Injection for more in depth info.

1 Like