CodeIgniter Forums
arguments to a controller instead of function - 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: arguments to a controller instead of function (/showthread.php?tid=31931)



arguments to a controller instead of function - El Forum - 07-07-2010

[eluser]coldfire82[/eluser]
HI,

I want to solve this problem without htaccess rewrite rules (if its possible).

I want this kind of url

Code:
http://site.com/<controller>/<argument>
e.g.
Code:
http://site.com/user/john

Here the argument is supposed to be for the index() function.
If I do,

Code:
http://site.com/user/index/john

then ofcourse it will work. But. does CI give some kind of solution for this...? if no, then can anyone write me a rewriteRule for this.

Thanks


arguments to a controller instead of function - El Forum - 07-07-2010

[eluser]mddd[/eluser]
If you ALWAYS want to go to the index method you can use this route:
Code:
$route['user/(.*)'] = 'user/index/$1';

This makes /user/john go to user/index/john. And you're done.

If you want to rewrite but also want to keep the possibility of other methods in the controller,
you can use the _remap method. If there is a _remap method in the controller, it is always executed!

Check the manual page about routes for more info.

Code:
function _remap($requested_method)
{
   // check if a function was requested that we know what to do with
   if ($requested_method=='list')
      // show a list of users

   else
      // the requested method isn't anything we know about, so treat it as a username that we show through the index method
      $this->index($requested_method);
}



arguments to a controller instead of function - El Forum - 07-07-2010

[eluser]coldfire82[/eluser]
yes, that solved the problem. But its a lengthy process if you have many funcitons in the controller. As you have to mention all the mehtod names and call them with their arguments.


arguments to a controller instead of function - El Forum - 07-07-2010

[eluser]mddd[/eluser]
Not neccessarily. There are functions you can use. Like method_exists():
Code:
if (method_exists($requested_method))
  $this->$requested_method();
This takes care of ALL the methods in your controller. If nothing is found, you can switch over to the generic case (e.g. looking up the user by name).