'Basic URL routing with parameters
I'm trying to build my own Routing classes to better understand PHP frameworks and to work with the MVC pattern. I've successifully built a routing system that can instantiate a controller and call a method from that particular controller.
My problem is now that I can't figure out how to call controller methods with parameters in the "pretty" url, like symfony does as I tried to understand.
I'm at this point:
$routes = "get" => [
"/" => [HomeController::class, "index"],
"/users" => [UsersController::class, "index"],
"/users/edit" => [UsersController::class, "edit"],
];
$response = $routes[$method][$path];
class Router {
....
public function dispatch($response) {
$controller = $response[0];
$action = $response[1];
$params = [];
$instance = new $controller();
call_user_func_array([$instance, $action], $params);
}
}
I would somehow like to add a third parameter to the $routes['get'] like this:
"/users/{user_id}/edit" => [UsersController::class, "edit", [{user_id}],
and then instantiate my controller calling the edit method with $user_id as a parameter
class Router {
....
public function dispatch($response) {
$controller = $response[0];
$action = $response[1];
$params = $response[2];
$instance = new $controller();
call_user_func_array([$instance, $action], $params);
}
}
class UsersController extends Controller {
....
public function edit($user_id){
echo "Editing $user_id";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
