klein / klein.php

A fast & flexible router
MIT License
2.66k stars 290 forks source link

Redirect to a different route #292

Open nickell opened 9 years ago

nickell commented 9 years ago

Hey, I am loving this router, thanks for making my life easier! I have a quick question about redirecting routes.

Say I have one route:

// This is inside $klein->with('/listings', 'listingsController.php');
$this->respond('POST', '/?', function($request, $response) {
    // I have populated the $request->user object from a JWT
    $response->redirect("/users/$request->user->id/listings")->send();
});

And here's the route I'd like to redirect to:

// This is inside $klein->with('/users','usersController.php');
$this->respond('POST', '/[:id]/listings', function($request, $response) {
    // Do stuff with the POST variables
});

Due to the nature of redirecting (sending a new Location header), when that redirect is fired, that second route would match if it were accepting the GET method. I'm looking for a way to redirect (or "reroute") without making another round trip so that I don't lose the original POST vars. Any ideas?

rekcuFniarB commented 5 years ago

It's simple with non anonymous functions:

// Routes
$this->respond('POST', '/?', array($listings, 'main'));

$this->respond('POST', '/[:id]/listings', array($users, 'listings'));

And in $listings->main() which handles first route, you call return $users->listings($request, $response);, which handles the second route.