0

How can I create dynamic, arbitrary routing with codeigniter? So, the default routing system(controller/method) works for me, for the most part. However, I'd like to give the website owner the ability to create arbitrary friendly URLs for any controller within the website.

For example, if this website has a controller that handles articles, a normal address of any given article would be

example.com/articles/read/23421

and if it had another controller that dealt with products, a given product would typically live at

example.com/products/view/234234

However, I want, in addition to this, to give the website owner the ability to say "ok, so article 23421 will now be accessible in

example.com/my-vacation-in-vegas

and product 234234 will live in

example.com/flat-screen-tv

Is there anything that I could do to achieve this functionality? Presently, the routing system, as I understand it, is fixed and I would have to hardcode it in routes.php for every item like that.

Thanks!

Northern
  • 113
  • 7

1 Answers1

0

To achive this you have to ensure ther is no cross table double name inserted I.E. if owner want to make and article named flat-screen-tv, before insert it should be checked if exists in both tables - not only in article table. Instead of that you can use different controller for each with appropriate uri segment that would make distinction of products and articles. It would looks like example.com/product/flat-screen-tv and example.com/article/flat-screen-tv - something similar to what you have now, but with slug in URL, not an ID. Second one (with [product|article] uri segment) would be recommended because first one doesn't follow S in SOLID and would be slower to query with upraising number of products and articles. For inserting and getting slugs from DB check answer here. Following assumption of built system you already have there (regarding premade URIs you posted), your routes in APPPATH.'config/routes.php' can be like:

$config['article/(:any)'] = 'article/read/$1';//here $1 is slug and not id which you have to change in Article controller, read() method as in Q/A link i posted above
$config['product/(:any)'] = 'product/view/$1'; same logic as in previous route
// By personal affinity I used singular for product and article

Routing system is not fixed that much and you can use wild cards for your routes such are (:any), (:num) or even regex. Suma sumarum, you have to store slugs for articles and products that'd be used for creating URLs.

Community
  • 1
  • 1
Tpojka
  • 6,996
  • 2
  • 29
  • 39