1

I'm starting out with CI and there's something I don't understand. I'm writing this login page and I'd like to add the users object to the session. How do I do that? The user object comes from my user model.. For a new instance I write:

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

but this won't work:

$this->session->set_userdata('userobject', $this->user);

Any ideas how this is done?

3
  • It's generally a good practice to avoid storing any model objects in the session (mainly due to loading reasons). The other issue is that when the user visits a page you'll almost always want to check that they haven't been banned or updated in another tab :) I generally just store the user's ID and query the DB on every page. Commented Sep 4, 2010 at 18:54
  • Why do you need two instances of the same model? Commented Sep 4, 2010 at 20:41
  • so I could compare those objects would be an example... I'd like to add the object to the session, it's more practical imo, but if I can't find how to do it i'll go with th userid Commented Sep 4, 2010 at 21:43

2 Answers 2

2

In the user Model create a function for retrieving the user data you want to add to session:

function get_user_data($id){
    //example query
    $query = $this->db->get_where('mytable', array('id' => $id));
    //might wanna check the data more than this but...
    if ($query->num_rows() > 0){
        return $query->row_array();
    }
    else{
        return false;
    }
}

In the controller:

$this->load->model('user_model', 'user');
$user_data = $this->user->get_user_data($id);
if(!empty($user_data)){
    $this->session->set_userdata($user_data);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't even think of using an array, I was thinking of an instance from my class. Thank you.
Saving only the data = you can't use the object's function.
1

What about serializing your model ;-)

$this->session->set_userdata('userobject', serialize($this->user));

and then unserialize it when fetching. But, be warn of CI session, it doesn't use the native PHP session, it used the limited size of cookies.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.