Routing rules are defined in your application/config/routes.php file.
There is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:
example.com/class/function/id/
In some cases, you may want to remap this relationship so that a different class/method can be called instead of the one corresponding to the URL.
To learn how to implement routers on a real-world project, we will assume that we are creating an application for managing contact details. The following table shows the URLs that will be working with.
| No. | URL | Route | Controller | Method |
|---|---|---|---|---|
| 1 | / | $route[‘default_controller’] | Contacts | index |
| 2 | /contacts | $route[‘contacts’] | Contacts | list |
| 3 | /contacts/add | $route[‘contacts/add’] | Contacts | add |
| 4 | /contacts/edit/id | $route[‘contacts/edit/(:num)’] | Contacts | edit |
| 5 | /contacts/update/id | $route[‘contacts/update/(:num)’] | Contacts | update |
| 6 | /contacts/delete/id | $route[‘contacts/delete/(:num)’] | welcome | delete |
Create URLs for Applications
create routes for our project. Open application/config/routes.php
$route['default_controller'] = 'contacts'; $route['contacts'] = 'contacts/list'; $route['contacts/add'] = 'contacts/add'; $route['contacts/edit/(:num)'] = 'contacts/edit/$1'; $route['contacts/update/(:num)'] = 'contacts/update/$1'; $route['contacts/delete/(:num)'] = 'contacts/delete/$1'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE;
The following table shows the respective URLs obtained from the above-defined routes
| No. | Route | URL |
|---|---|---|
| 1 | $route[‘default_controller’] = ‘contacts’; | http://localhost |
| 2 | $route[‘contacts’] = ‘contacts/list’; | http://localhost/contacts |
| 3 | $route[‘contacts/add’] = ‘contacts/add’; | http://localhost/contacts/add |
| 4 | $route[‘contacts/edit/(:num)’] = ‘contacts/edit/$1’; | http://localhost/contacts/edit/1 |
| 5 | $route[‘contacts/update/(:num)’] = ‘contacts/update/$1’; | http://localhost/contacts/update/1 |
| 6 | $route[‘contacts/delete/(:num)’] = ‘contacts/delete/$1’; | http://localhost/contacts/delete/1 |
