tc-php-mvc-core
tc-php-mvc-core copied to clipboard
Router parameter
Hey there,
user/update/1
or product/{:slug}
or category/{:slug}/{:id}
When we define a route in the form of, we cannot access the '1' or 'slug' parameter other than using the $ _GET global. We send Request and Response classes as parameters to the controller. Likewise how can we send this '1' or 'slug' parameter?
It might be a year after the question, but it worth sharing the way I did it (using preg_match) first : index.php
- add the route as this -- $app->router->get('#^/Customers/(\d+)$#',[CustomersController::class,'getCustomerProfile']);
second : Router.php
- add array of params to the class : array $params = [];
- in resolve method, if $callback==false add this code -- $route_found = false; foreach ($this->routes[$method] as $path1=>$route1) { if (preg_match($path1, $path, $matches)) { $callback = $this->routes[$method][$path1]; $this->params = $matches; $route_found = true; break; } } if(!$route_found){ throw new NotFoundException(); }
third : in controller add third parameter to your method as array public function getCustomerProfile(Request $request, Response $response, array $params){ $customer_id = $params[1]; // do not use 0 it will be the path // check if not null and do your thing }
An update to the project was made by @thecodeholic. Check out #5
I built my own PHP MVC framework; inspired by this project. Thank you @thecodeholic
Amazing @virtual-designer. Love to hear such stories. Thank you
Amazing @virtual-designer. Love to hear such stories. Thank you
Thanks sir! Here is my project link: https://github.com/onesoft-sudo/invention-project
You got your first star from me. I will explore the project as soon as I have time. Cheers... Don't call me sir. Call me Zura. :)
@thecodeholic Ok Zura. But you're a great man. You made my day :)
I built my own PHP MVC framework; inspired by this project. Thank you @thecodeholic
I am trying to do that too. Its really cool to have such materials to work with