Draex_ Draex_ - 6 months ago 56
PHP Question

Completely dynamic URLs in CodeIgniter

I'm building an online store based on CodeIgniter. I'd like URLs to look like this?


The thing is there are also non-product pages like
and these still have to work.
What's the best way to achieve this?


Routes that you define in your routing config file (application/config/routes.php) are obeyed in the order that they are defined. If you put in your more specific routes first, then a generic catch-all route can be employed at the end.

$routes['checkout/step_(\d+)'] = 'checkout/step_$1';
// calls the checkout class, step_x method

$routes['(.*)/(.*)'] = 'product_class/product_method/$1/$2';
// calls the product class, and product method, passing category and name as parameters

The disadvantage to this approach is that you will have to define all of your routes in this file, even the ones that map directly to controller/action. A better approach might be to make your product routes start with 'product', so that they looked like this:


With this approach you can define a routing rule that will only be applied to products like this:

$routes['products/(.*)/(.*)'] = 'product_class/product_method/$1/$2';

This is better because it does not force you to define concreate routes for every controller/action combination in your site.