How to send variables to Bramus Router
✔ Recommended Answer
The problem you're looking at here is a PHP scoping issue, not a specific bramus/router
– which I'm the author of – issue. Since you define $user
inside the before callable, it's only available inside its current scope (e.g. between the {
and the }
of the function). Therefore you cannot access it outside of said function.
There are several ways to solve this. Since I see you already inject an $app
variable into the before callback and other functions, I suggest you store the $userid
onto $app
and always read it from there.
Something like this:
.... $router->before('GET|POST', '/api.*', function() use ($app) { $app->set('userid', '12345'); }); // Check for read:messages scope $router->before('GET', '/api/private-scoped', function() use ($app) { if (!$app->checkScope('read:messages')){ header('HTTP/1.0 403 forbidden'); header('Content-Type: application/json; charset=utf-8'); echo json_encode(array("message" => "Insufficient scope.")); exit(); } }); $router->get('/api/users/get-info/(\w+)', function($userid) use ($app) { header('Content-Type: application/json; charset=utf-8'); echo json_encode($app->getUserInfo($userid)); }); $router->get('/api/users/test', function() use ($app) { header('Content-Type: application/json; charset=utf-8'); echo json_encode(array("user" => $app->get('userid'))); });....
Source: stackoverflow.com
Answered By: Bramus
To send variables to Bramus Router in PHP, you can use placeholders in the route patterns to capture the values from the URL, and then pass them to the controller method as arguments. Here's an example of how to do it:
- Define a route with a placeholder in the pattern, for example:
php$router->get('/users/{id}', 'UserController@show');
In this example, {id}
is a placeholder that captures the value of the id
parameter from the URL.
- Define the corresponding controller method that will handle the route, for example:
phpclass UserController {
public function show($id) {
// Your logic here, using the $id variable as needed
}
}
The controller method takes the captured id
value as an argument.
- When the route is matched, Bramus Router will automatically pass the captured parameter value to the controller method as an argument. You can then use the value in your logic as needed.
For example, if the URL is example.com/users/123
, Bramus Router will call the UserController@show
method and pass the value 123
as the $id
argument. You can then use this value in your controller method to fetch the corresponding user data from the database, or perform any other logic that depends on the user ID.
Note that you can use multiple placeholders in a single route pattern, and Bramus Router will pass all captured values as separate arguments to the controller method. For example, if the route pattern is /users/{id}/posts/{post_id}
, the corresponding controller method would take two arguments, $id
and $post_id
, in that order.
Comments
Post a Comment