March 24, 2012

Codeigniter controller and model with same name collison

Question by musa

I’m try something from this comment idea Code Igniter Controller/Model name conflicts

find class name variable on core/CodeIgniter.php :

$class = $RTR->fetch_class(); and change like that:
$class = 'Controller' . $RTR->fetch_class();

now change controller name:

class ControllerUser extends CI_Controller { ...

It works, now I can use User model and User controller. But my question is, Does it make sense? or Does the problem? (sorry my bad English)

Answer by Starx

To get around this issue, normally most people add the ‘_model’ suffix to the Model class names

I think it is better to add a suffix to the Controllers instead, since they are almost never referenced by their class names in your code.

First we need to extend the Router class.

Create this file: “application/libraries/MY_Router.php”

class MY_Router extends CI_Router {
    var $suffix = '_controller';

    function __construct() {
        parent::CI_Router();
    }

    function set_class($class) {
        $this->class = $class . $this->suffix;
    }

    function controller_name() {

        if (strstr($this->class, $this->suffix)) {
            return str_replace($this->suffix, '', $this->class);
        }
        else {
            return $this->class;
        }

    }
}

Now edit “system/codeigniter/CodeIgniter.php”

line 153:

if ( ! file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->controller_name().EXT))  

line 158:

include(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->controller_name().EXT);  

Next, edit: “system/libraries/Profiler.php”, line 323:

$output .= " 
<div style="color:#995300;font-weight:normal;padding:4px 0 4px 0">".$this->CI->router->controller_name()."/".$this->CI->router->fetch_method()."</div>";  

Source

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!