router
router copied to clipboard
Redirect to another route
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
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.
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?
That can work for GET
requests (but, as you say: it'll be an extra request) but not for POST
requests.
[ 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');