Setting up routes is all well and good but when you change the route you need to run around your application changing all links to it.
I made a small modification that will allow you to link to the normal URI then have it output the route in the URL.
An example of supported routes:
$route['edit-settings'] = "users/settings/edit";
$route['page-:any-:any'] = 'pages/$2/$1';You can then use:
<?=anchor('users/settings/edit', 'Edit Setting');?>and it will link you to http://example.com/edit-settings.html.
Here is the code in the form of an extended MY_url_helper.php.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter URL Helpers - Extended
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author Philip Sturgeon
*/
// ------------------------------------------------------------------------
/**
* Site URL
*
* Create a local URL based on your basepath. Segments can be passed via the
* first parameter either as a string or an array.
*
* @access public
* @param string
* @return string
*/
if ( ! function_exists('site_url'))
{
function site_url($uri = '')
{
include(APPPATH.'config/routes.php');
// Is there a literal match? If so we're done
if (in_array($uri, $route))
{
$uri = array_search($uri, $route);
}
else
{
foreach ($route as $key => $val)
{
if(!$key or !$val) continue;
preg_match_all('#(:any|:num)+#', $key, $rules);
preg_match_all('#\$([0-9]+)#', $val, $references);
if(empty($rules[0]) or empty($references[0])) continue;
for($i = 0; $i < count($rules[0]); $i++)
{
$key = substr_replace($key, $references[0][$i], strpos($key, $rules[0][$i]), 4);
$val = substr_replace($val, $rules[0][$i], strpos($val, $references[0][$i]), 2);
}
$val = str_replace(':any', '(.+)', str_replace(':num', '([0-9]+)', $val));
// Does the RegEx match?
if (preg_match('#^'.$val.'$#', $uri))
{
$uri = preg_replace('#^'.$val.'$#', $key, $uri);
}
}
}
$CI =& get_instance();
return $CI->config->site_url($uri);
}
}
/* End of file url_helper.php */
/* Location: ./system/helpers/url_helper.php */
?>
Note: This only works with static routes and routes using :any or :num. That means if you use regex in your route it WILL NOT WORK. This is something I will look into, but not right now.