Lukas Oppermann
Lukas Oppermann

Reputation: 2938

CodeIgniter library multiple instances

I have got a problem with my codeigniter library. To transform database data into a navigation and have active elements and such like I build a library class CI_Navigation(). It works perfectly fine, I just have one problem.

Often on webpages one has corresponding but separated navigations e.g. a main navigation at the top and a subnavigation on the side. To get around that I can initialize my class with a parameter telling it which levels this navigation is to hold. I would for example do something like this.

$this->load->library('Navigation');

$main = $this->navigation->build( array('levels'=>array(0)) );
$sub = $this->navigation->build( array('levels'=>array(1,2)) );

As you might expect it does not work, because the data in the class stays the way it was assigned by the first call of build.

Sadly enough in CodeIgniter Libraries are singletons (right? that’s what I read). So I can not initialize it twice like:

$this->load->library('Navigation','','main');
$this->load->library('Navigation','',sub);

Do you have any idea how I can overcome this problem.

It should work if I would use arrays for the variables used in the class right? E.g. for the options instead of using $this->option I would have to dynamically create $this->$option[0], $this->$option[1].

Does this work? I can not test it at the moment but will do so tonight. But this is not a really elegant way, so is there a better way to solve this? Is there any way i could initialize the library multiple times?

Thanks in advance guys.

Upvotes: 2

Views: 4847

Answers (2)

miro
miro

Reputation: 780

Alternatively you can do stuff like this:

$this->load->library('navigation');
$this->another_navigation = clone($this->navigation);

Upvotes: 0

Elliot
Elliot

Reputation: 1616

If you want to stick the strict CI library implementation, then I would suggest that you make your class parameters an array of configurations; and then specify the configuration you want to use in your 'build' function.

$options = array
(
  'main' => array('level' => 0),
  'sub' =>array('level' => 1)
);

$this->load->library('navigation', $options);

$main_nav = $this->navigation->build('main');
$sub_nav = $this->navigation->build('sub');

But I often revert to standard objects for this sort of thing:

$a_navigator = new Navigation($options_a);
$b_navigator = new Navigation($options_b);

$a_tree = $a_navigator->build();
$b_tree = $b_navigator->build();

unset($a_navigator);
unset($b_navigator);

Upvotes: 7

Related Questions