Welcome Guest, Not a member yet? Register   Sign In
Why Can't $this->load->library() Be Invoked in Model Constructor?
#1

[eluser]Morgan Cheng[/eluser]
I'm ramping up with Twitter API. I found that below code doesn't work.

Code:
class TimeLine_Model extends Model {
    public function __construct() {
        parent::__construct();
        $this->load->library('twitter');
        $this->twitter->auth('username', 'password');
    }

    function getFriendsTimeLine() {
        $timeline = $this->twitter->call('statuses/friends_timeline');
        return $timeline;
    }
}

The error is indicating that "$this->twitter" in constructor is null.
Quote:: Call to a member function auth() on a non-object in ....\***.php on line 8

It seems that
Code:
$this->load->library
doesn't work in constructor. Why?

I originally plan to make a customized MY_Model and have
Code:
$this->twitter
initialized in the constructor. Then, all my models can inherits from that MY_Model.

If
Code:
$this->load->library
doesn't work in constructor. How to workaround it?
#2

[eluser]steelaz[/eluser]
You need to create CI instance in the model if you want to load and access libraries.

Code:
class TimeLine_Model extends Model {
    private $CI = NULL;

    public function __construct() {
        parent::__construct();

        $this->CI = &get;_instance();
        $this->CI->load->library('twitter');
        $this->CI->twitter->auth('username', 'password');
    }

    function getFriendsTimeLine() {
        $timeline = $this->CI->twitter->call('statuses/friends_timeline');
        return $timeline;
    }
}
#3

[eluser]Morgan Cheng[/eluser]
@steelaz, why below code works?
The only difference is $this->load->library is invoked not in constructor.

Code:
class TimeLine_Model extends Model {

    function getFriendsTimeLine() {
        $this->load->library('twitter');
        $this->twitter->auth('username', 'password');

        $timeline = $this->twitter->call('statuses/friends_timeline');
        return $timeline;
    }
}
#4

[eluser]steelaz[/eluser]
Not sure, I always thought it wouldn't. BTW, this method looks like it should be in a library, not in a model.
#5

[eluser]frist44[/eluser]
just for the record, I load all of my libraries/helpers/models in the constructor of the appropriate file. $this should certainly work in all your views/controllers/models.




Theme © iAndrew 2016 - Forum software by © MyBB