开发者

Why does code igniter not segregate class types?

When you are using code igniter you load a library or model like so

$this->load->library('mylibrary');  
$this->load->model('mymodel');

So开发者_如何转开发, in a real world example, lets say you have a controller called user.

So, to login a user you send them to http://example.com/user/login

Now the login function loads a form that submits to http://example.com/user/login_do You do some simple checks, and then send it over to your model to do the database check for you.

So you call

$this->load->model('user');
if($this->user->validate($email, $pass)){...}


UH OH!

Fatal error: Cannot redeclare class User in /var/www/unity/src/application/models/User_Model.php on line ...

So what happened? Well, Code igniter does not segregate the classes, so your model now conflicts with your controller,

sure you can use

$this->load->model('user_model', '', 'user_m');
if($this->user_m->validate($email, $pass)){...}


So, Onto my question.

Why does code igniter not segregate the classes, e.g. so you would call

$this->load->model('user');
if($this->model->user->validate($email, $pass)){...}

Sure it's slightly longer, but hell it would make things heaps nicer to user. is it possible to extend code igniter so it works in this way?


It's not exactly the solution you're asking for (or a great idea), but there's nothing stopping you from doing this:

class Users extends CI_Controller {

    private $model;
    private $m;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->model->users = $this->user_model;
        $this->m = $this->user_model;
    }

    function index()
    {
        // Here's that syntax you wanted
        $this->model->users->get_many();

        // Even shorter
        $this->m->get_many();
    }

}

You can really just assign anything to any property of the controller you want, as long as it's not the name of a loaded class or property (session, router, etc.). It can save you some typing if your model names are really long, but otherwise it's pointless and may conflict with things in the future.

Here's what I do if I'm not using *_model for model names:

  • Controller name: Users (plural)
  • Model name: User (singular)

No conflict, short syntax, sensible naming, it just doesn't work for some names like "news".

As I mentioned, it would be nice to see controller names using something like Controller_User or User_Controller to clear up the namespace issues a bit for the classes that we actually do have to call frequently, like models and libraries, but keep our urls as normal. I'm sure it can be done, something for a rainy day...


You missing the main point, PHP doesn't allow two classes with the same name, basically that's what Cannot redeclare class User says.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜