router icon indicating copy to clipboard operation
router copied to clipboard

Redirect to another route

Open plckr opened this issue 3 years ago • 4 comments

Hey, nice library!

I have been stuck finding an answer.

What I Want:

$router->get('/([a-z0-9_-]+)', function($slug) {
    // Code to find the id
    $router->callRoute(...); // Some way to call the other route, giving the id as parameter
});

$router->get('/(\d+)', function($id) {
    // Code
});

What I did so far:

function perId($id) {
    // Code
}

$router->get('/([a-z0-9_-]+)', function($slug) {
    // Code to find the $id
    perId($id);
});

$router->get('/(\d+)', function($id) {
    perId($id);
});

I don't know if I can accomplish the same with the before() function Please give me your opinion

plckr avatar Apr 07 '21 08:04 plckr

Forwarding calls to other handlers is currently not supported.

What you can do is something like you put together there: convert the slug to an id, and then call the perId method.

Using a before this is not possible, as they can't manipulate params in between their execution and the route handling. The concept of param converters would allow this. I'll happily accept a PR that provides this.

bramus avatar Apr 08 '21 10:04 bramus

Thanks for your reply.

I could add a Redirect HTTP Header to the appropriate route, but that requires a 2nd connection in client side, do you think it's a good approach or I should avoid it?

plckr avatar Apr 08 '21 13:04 plckr

That can work for GET requests (but, as you say: it'll be an extra request) but not for POST requests.

bramus avatar Apr 08 '21 13:04 bramus

[ Just thinking → no implemented solution yet ]

I would say you can give routes optional names, and you can call them by that

$router->get('/route(/.*)?', function() {
    // do something
    $router->callRoute(Router::GET_REQUEST, 'someelse', 'value', 'value2');
});

$router->get('/somethindelse', function(... $values) { // idk if ... existed in php 5.6 🤔  
    var_dump($values); // value, value2
}, 'someelse');

uvulpos avatar Apr 10 '21 10:04 uvulpos