I'm developing a site with codeigniter. Now, normally when you use a class in codeigniter, you basically use it as if it were a static class. For example, if I head a model called 'user', I would first load it using

$this->load->model('user');

and than, I could invoke methods on that user class like

$this->user->make_sandwitch('cheese');

in the application that I'm building, I would like to have one UserManagement class, which uses a class called 'user'.

so that, for example I could

$this->usermanager->by_id(3);

and this would return an instance of the user model where the id is 3. What's the best way to do that?

Comments

The best way is to use an ORM. Doctrine is popular one, and there are some tutorials on integration it with CodeIgniter

Written by bassneck

@bassneck thx for your suggestion. I'm probaly not going to use that in my current project, but I'll definitely look into doctrine, it looks awesome at first glance.

Accepted Answer

The model classes in CI are not quite the same thing as model classes in other syntax's. In most cases, models will actually be some form of plain object with a database layer which interacts with it. With CI, on the other hand, Model represents the database layer interface which returns generic objects (they're kinda like arrays in some ways). I know, I feel lied to too.

So, if you want to make your Model return something which is not a stdClass, you need to wrap the database call.

So, here's what I would do:

Create a user_model_helper which has your model class:

class User_model {
    private $id;

    public function __construct( stdClass $val )
    {
        $this->id = $val->id; 
        /* ... */
        /*
          The stdClass provided by CI will have one property per db column.
          So, if you have the columns id, first_name, last_name the value the 
          db will return will have a first_name, last_name, and id properties.
          Here is where you would do something with those.
        */
    }
}

In usermanager.php:

class Usermanager extends CI_Model {
     public function __construct()
     {
          /* whatever you had before; */
          $CI =& get_instance(); // use get_instance, it is less prone to failure
                                 // in this context.
          $CI->load->helper("user_model_helper");
     }

     public function by_id( $id )
     {
           $q = $this->db->from('users')->where('id', $id)->limit(1)->get();
           return new User_model( $q->result() );
     }
}
Written by cwallenpoole
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki