简体   繁体   中英

Php Routing Url with parameters

I try to parse my Url to my Router Class. For the begin all is clear i get my Url splitting it into a Array but my Problem at the moment is that i need to add my Routes first like $router->add("user/show/123"); or $router->add("article/2584/edit"); pushing them into a Array and request when its in Array then load Page. But i dont find a way to solve the Parameters when i add them to the Routes. How can i make it like $route->add("article/WHATEVER/edit"); so its loading the Page whatever the number is? I guess with RegEx but iam not really good at it or understanding it. And have no Idea at the moment how to do it i already googled and searched but all i find are finished classes which i dont want to use cause i want to understand how it works at least.

I would be happy for some help some links and some Code Snippets which will give me a new Point of View and a way to go on.

I did mine in a slightly different way. I take URI's in the following form:

/controller/action/param1/param2/param3/etc.

I route this to index.php?q= using .htaccess, so the entire string becomes accessible by invoking $_GET['q']. I split the string into pieces by using explode with / as a delimiter and the first and the second elements are always the controller and action. Everything else is one string (regardless of parameters) and gets forwarded to the relevant function (action) using a callback. In my function (eg. view) I have $param as an argument, and $param is a string containing /param1/param2/param3/etc.

Within the function, I further split this string into individual parameters, assigning them to regular named variables as needed.

$param = explode('/', $param);
$id = $param[0];
$sortBy = $param[1];
$sortOrder = $param[2];
etc.

Obviously, I check the parameters for validity and use default values if they're empty. The only disadvantage I see is that you MUST provide all 2, 3, 4 (however many you have) parameters you have, even if you want to change only one. In my above example, where I have 3 params, if I only want to change sortOrder, my URI would look something like:

/controller/action/0/0/ASC

Using PHP, I detect that 0 is not a valid parameter for that action and assign it a default value from my settings or other source. The great advantage is simplicity, but also the unlimited number of params you can use for each module. You don't have to "add routes" as these are processed within the controller, not the route file.

PS: I know this is not best practice and it's a very rudimentar approach, but it works. Depending on how far you want to take this, this option might not work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM