I’m using PHP and ToroPHP for routing.
Unknown number of child pages
It works fine, but in my case I can add pages with childs and parents, where a parent can have an unknown number of have childpages.
In ToroPHP it might look like this:
// My Path: http://www.test.com/product/house/room/table/leg/color/
Toro::serve(array(
"/" => "Home",
"/:string/:string/:string/:string/:string/:string/" => "Page"
));
class Page {
function get($slug, $slug2, $slug3, $slug4, $slug5, $slug6) {
echo "First slug: $slug";
}
}
Problem
-
I can figure out what the maximum depth can be and then loop and append
out a string containing the “/:string” parameters but it don’t look
that nice. -
The get-function in the Page-class takes an unknown number of in
parameters. I can calculate the max depth from outside the function, but I need the function to know how many values to take.
Question
- Is there an alternative way the the problem 1? Some regular expression maybe?
- How can I make a function take an unkown number of in parameters?
- Maybe I try to solve this the wrong way and the first two questions are not relevant? Correct me if that is.
In order for your action to receive all parameters, you need to capture them in your regex. You capture a value in regular expressions using parentheses.
:stringis just an alias for([a-zA-Z]+). You could apply a wildcard after the first segment, like this:However, this means that you need to parse the URL by yourself in your action, which is not very clean either.
If you want to make this particular case more clean, an option would be to use str_repeat:
ToroPHP is a very simple library, it should not be that hard to fork it and bend it to your will. Ideally, how would you like to define routes like this? Maybe a route like
/:string*6?You can always pass more or fewer parameters than defined to a PHP function. Use func_get_args to get all passed parameters and func_num_args to get the number of passed parameters.