1

I am trying to route a url as follows:

domain.com/param/some_controller/method/

mapped to

some_controller::method($param)

I am not skilled with regular expressions, which i'm fairly certain are necessary, so I would really appreciate it if someone could help get me started? Or point me to a good tutorial or example?

2
  • Is domain.com/param/some_controller/method/ the string that's populated into a certain variable? Like, can I assume the http(s):// protocol will never be there, and the string will always be in that exact format, or not? (I'm not familiar with CI.) Commented Jun 22, 2011 at 2:41
  • @Wiseguy - all of that is handled by CI, and there is also some rewrite rules so the url is actually domain.com/index.php?param/some_controller/method Commented Jun 22, 2011 at 3:27

3 Answers 3

2
$route['(:any)/some_controller/method/'] = "some_controller/method/$1";

if your param is a number use (:num) instead.

in your controller

function method($my_param) {
    echo 'my param is '. $my_param;
}

an RL example:

$route['(:num)/blog/entry/'] = "blog/view/$1";

class Blog extends CI_Controller {

    function view($id) {
         echo 'fetching blog entry no ' . $id;
    }
}

your view will look like

view.php

<html>
<body>
link to <?= anchor('1/blog/entry/','my first post'); ?>
link to <?= anchor('2/blog/entry/','my second post'); ?>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

1

This is a little messy, because there is currently no way to do this with routing without confusing things. You can try this:

$route['([^/]+)/([^/]+)/([^/]+)'] = "$2/$3/$1";

BUT what this says is that it will apply to ANY url: this will confuse regular controllers. You are better served adding some prefix to identify requests you should process with this route: for example

$route['a/([^/]+)/([^/]+)/([^/]+)'] = "$2/$3/$1";

3 Comments

what if I were to just order all regular controllers above this? don't they take to the first route that matches?
Well, if you listed EVERY URL you could possibly get above this, then yes. That seems like it would be a pain for large numbers of URLs but if you only have 5 or 10 or perhaps even 20 it wouldn't be terrible.
@ Femi - Yea, most likely less than 5, probably only 2 or 3 exceptions to this route! I will try your method soon
0

Same effect, but Codeigniter-style:

//remember that custom routes need to go _after_ ci's default routes, as they're executed in the order you provide them
$route['default_controller'] = "welcome";
$route['404_override'] = '';
//exception 1 to your regex here
//exception 2 to your regex here
//so on...
$route['(:any)/(:any)/(:any)'] = "$2/$3/$1";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.