Welcome Guest, Not a member yet? Register   Sign In
Load class but not initiate it
#1

[eluser]Rubain[/eluser]
Hi,

I was wondering, the $this->load->library() automatically initiates an object.

But I sometimes have to create a lot of objects. Is it a good style to put $this->load->library in a loop?

It feels like no-go. I could use the require_once and give in the relative path, but that doesn't seem to be the CI style also.

Is there an elegant way?

Thanks
#2

[eluser]Phil Sturgeon[/eluser]
There is no built in way to do this. Why would you want to load a library if you are not planning on using it?
#3

[eluser]Rubain[/eluser]
So let's say I'm reading a lot of advertisements from some RSS feed.

Pseudocode:
Code:
foreach($advertisementsArray as $rawAdvertisement) {
     $this->load->library('advertisement', $rawAdvertisement, $outputArray[]);
}

This doesn't cause an overhead?

I was looking for something like

Code:
Load class Advertisement
foreach(...) {
   $outputArray[] = new Advertisement($rawAdvertisement);
}

EDIT:

Another example: I have a custom Exception, how do I load it, and throw it? This looks strange...
Code:
$this->load->library('BadConstructorCallException', array("reason" => "test"), 'ex');
throw $this->ex

Thanks!
#4

[eluser]bigtony[/eluser]
You could load your library just before the loop starts and then in each repetition call a function that is defined within that library, passing your changing parameters.
#5

[eluser]Rubain[/eluser]
So some kind of AdvertisementFactory, and call a function createAdvertisement(params)?

Is the way I use the exception ok?
#6

[eluser]Phil Sturgeon[/eluser]
Using your first structure is basically the same as the next. It performs one single in_array() check to see if the file is already loaded and only includes it if its not already in there. Really doesn't add that much overhead.

Code:
foreach($advertisementsArray as $rawAdvertisement) {
     $this->load->library('advertisement', $rawAdvertisement, $outputArray[]);
}

How would this work? Does your constructor return a string? Can they even do that? heh. Seems like odd syntax.

Code:
$outputArray[] = new Advertisement($rawAdvertisement);
#7

[eluser]Rubain[/eluser]
Why do you think it returns a String? I didn't tested it.

Thanks for the answers! I didn't knew it was a good style of using it that much. I thought it was only used for singleton classes. If anybody knows a shorter way of throwing a homemade Exception, please tell me.

Thanks




Theme © iAndrew 2016 - Forum software by © MyBB