Welcome Guest, Not a member yet? Register   Sign In
Proper place to load libraries
#1

[eluser]tomjnsn[/eluser]
Can libraries only be loaded in the constructor of a controller?

Thanks,

Tom
#2

[eluser]tomjnsn[/eluser]
I should clarify: I'm referring to the upload library (in 1.7.0). If I try and load it, as the example shows, in a regular method of the class it nests it somewhere below other libraries. If I put it in the constructor it loads just fine. Here's a sample Controller I created:

class Test extends Controller {
function Test() {
parent::Controller();
// doing this here the upload library is available via $this->upload
// $this->load->library('upload');
}

function index() {
// Doing this here the upload library is nested under other libraries
$this->load->library('upload');
die(print_r($this));
}
}

I'm using PHP 5.2.6, with Apache 2.2.9 on Windows XP if any of that makes any difference.

Thanks,

Tom
#3

[eluser]GSV Sleeper Service[/eluser]
no, you can load them in any method you want. only load it in the constructor if you're going to need it in every method.
#4

[eluser]Phil Sturgeon[/eluser]
There is no single correct place to load a library.

Autoload if you need it EVERYWHERE.
Controller __construct() if you need it in every method of that controller
Controller method() if you only need it in a few methods here and there.

I also like to load libraries from other libraries if they require the. A lot of old C++ developers around here get angry about that, but I think loading dependent libraries wherever they are needed makes sense, especially as CI will only include and instantiate the classes once.
#5

[eluser]tomjnsn[/eluser]
Thanks for the clarification. If you'll look at the post I made directly below with the sample class I show where I'm having a problem and I'm wondering what I'm doing wrong. I don't want to load the upload library for every method, just one method.

Basically if I load the library in a method it puts upload underneath encrypt->CI so I can access it by $this->encrypt-CI->upload but not $this->upload. If I load the library in the constructor though it loads it in the correct place so I can access it via $this->upload.

I stripped it down to the test class I posted above to confirm it wasn't some other piece of code I was doing. Could someone else confirm whether or not they get the same problem with the test code?

Thanks,

Tom




Theme © iAndrew 2016 - Forum software by © MyBB