Summer
Summer

Reputation: 2498

Load a library in a model in CodeIgniter

Why won't my model load the encryption library?

class User_model extends Model {

  function User_model() {
    parent::Model();
    $this->check_login();
  }

  function check_login() {
    $this->load->library('encrypt');
    $email = $this->encrypt->decode($email);
    ....
  }
}

This giving me a PHP error: Call to a member function decode() on a non-object on line X -- where X is the $this->encrypt->decode($email); line?

Edited to show that the problem was that check_login was called from the constructor

Upvotes: 13

Views: 30814

Answers (6)

zee
zee

Reputation: 1

i was also facing issue about facebook api, then I tried required_once the lib file of facebook in model. it worked for me.

require_once "application/libraries/facebook.php"; then make its object if you need.

Upvotes: 0

themightysapien
themightysapien

Reputation: 8379

you might want to change the name of the object for the library you are loading beacause CI also has got the encrypt class

just do

$this->load->library('encrypt',NULL,'myencryptobj');
$this->myencryptobj->yourfunction();

Hope this helps

Upvotes: 0

bingjie2680
bingjie2680

Reputation: 7773

I have tried many of them, but in the end, what I did is this in a model:

$this->load->library('mylib');
$mylib= new Mylib();
$mylib->somemethod();

This works for me.

Upvotes: 5

Phil Sturgeon
Phil Sturgeon

Reputation: 30766

Libraries should automatically be assigned to the Model instance so it should work fine.

Remember if you can't access the super-global you can always use $ci =& get_instance() to grab it at no extra cost to your memory.

But still... your code example should work >.<

Upvotes: 6

Pedro
Pedro

Reputation: 2927

You don't need to load the library in the MODEL, MODELS are always called from the CONTROLLERS so you just have to load the Libraries in the Controller, and the functions will be available in the models called from him!

Regards,
Pedro

Upvotes: 23

Summer
Summer

Reputation: 2498

I was calling check_login from within the constructor, and that was causing the problems.

The solution is to call $this->_assign_libraries(); right after loading a library in a constructor.

Thanks to this codeignitor forum thread: http://codeigniter.com/forums/viewthread/145537/

Upvotes: 5

Related Questions