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!

8 thoughts on “ Changing the default controller naming convention in CodeIgniter ”

    1. Just in case someone runs into the same problems as I did: unfortunately Emran forgot to name the constructors correctly (nothing to be ashamed of, Emran). So just replace “function MY_Router()” with “function __construct()” and “parent::CI_Router()” with “parent::__construct()”. I just spent 20 minutes wondering why on earth it isn’t working for me… and then I looked in the least obvious place. 🙂

Comments are closed.