CodeIgniter Forums
Routing - combing URL segments to form a method name? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Routing - combing URL segments to form a method name? (/showthread.php?tid=32344)



Routing - combing URL segments to form a method name? - El Forum - 07-20-2010

[eluser]Prophet[/eluser]
Hello all Smile

Is something like the following possible with CI's routing library?
Code:
$route['admin/product_required_details/(:any)/(:num)/(:any)'] = 'admin/product_required_details/$3_$1/$2';

For example, I would like:
Quote:admin/product_required_details/option/5/edit
...to route to:
Quote:admin/product_required_details/edit_option/5
(i.e. it should call the edit_option() method and pass 5 as the parameter.

Thanks in advance for any advice.


Routing - combing URL segments to form a method name? - El Forum - 07-20-2010

[eluser]KingSkippus[/eluser]
You could add somewhere close to the top of your option() function something like the code below. Note that I haven't tried it so there might be a syntax error or two, but it should work.

Code:
public function option($id, $subfunc) {
    // Check if $subfunc is a valid function name.
    if (isset($subfunc) && preg_match('/^[a-zA-Z_]\\w*$/', $subfunc)) {
        $redirect = $subfunc.'_'.__FUNCTION__;
        if (method_exists($this, $redirect)) {
            call_user_func(array($this, $redirect), $id);
        }
        else {
            // User specified a method that does not exist.
        }
    }
    else {
        // Subfunction not specified or was an invalid name.
    }
}



Routing - combing URL segments to form a method name? - El Forum - 07-21-2010

[eluser]mddd[/eluser]
I think prophet's own suggestion is fine by itself. In that example, the edit_option method would be called, no problem.
Routes are simply regular expressions, so if you rewrite the url that way, it will work just fine.


Routing - combing URL segments to form a method name? - El Forum - 07-21-2010

[eluser]Prophet[/eluser]
KingSkippus your solution worked perfectly, thank you. I tried my own solution and it didn't seem to work... If I can get CI's routing library to do the work for me that would be great, and much easier to maintain.


Routing - combing URL segments to form a method name? - El Forum - 07-21-2010

[eluser]KingSkippus[/eluser]
Per mddd's suggestion in another thread, you could also try the following:

Code:
$route['admin/product_required_details/([^/]+)/(:num)/([^/]+)'] =
    'admin/product_required_details/$3_$1/$2';