Changing the default controller naming convention in CodeIgniter

CodeIgniter is one of my favorite framework and I often use it for developing application quickly. Although it is very flexible in most cases, I find its naming convention to be strict. Many times I have faced this problem when my controller’s class name and a model/library’s class names are the same – a Fatal error is inevitable and I have to forcefully change the name of the conflicting class to something less desirable (say from Users to UsersModel). Today I wanted to end this problem.

So I extended the CI_Router core class and made change to the __validate_request_ method. Now I can name my controller classes in this fashion: UsersController and it resides on the file system as controllers/UsersController.php. If you’ve tried other established frameworks, you should notice that this naming convention is widely used. So, if you have the same need, then just download the MY_Router.php file and put it on your application/libraries folder. That’s it.

Here is how your controller would start:

[cc lang=’php’]

If you’d like to have a look at the code, here is the source for quick view:

[cc lang=’php’]
_suffix;

// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.’controllers/’.$segments[0].EXT))
{
return $segments;
}

// OK, revert to the original segment
$segments[0] = $orgSegments[0];

// Is the controller in a sub-folder?
if (is_dir(APPPATH.’controllers/’.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);

if (count($segments) > 0)
{
// Add suffix to the end
$segments[0] = ucfirst($segments[0]) . $this->_suffix;

// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.’controllers/’.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
// Add suffix to the end
$this->default_controller = ucfirst($this->default_controller) . $this->_suffix;

$this->set_class($this->default_controller);
$this->set_method(‘index’);

// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.’controllers/’.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = ”;
return array();
}

}

return $segments;
}

// Can’t find the requested controller…
show_404($segments[0]);
}
}
[/cc]

Cheers!