CodeIgniter Forums
Strange behaviour with custom library, my mistake? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Strange behaviour with custom library, my mistake? (/thread-51208.html)



Strange behaviour with custom library, my mistake? - El Forum - 04-24-2012

[eluser]CARP[/eluser]
Hi

I'm working with latest CI, and creating a custom library
I load my library from a view, as:

Code:
$this->load->library("mymsg");
echo $this->mymsg->myFunction();

I get:

Quote:Call to a member function myFunction() on a non-object

But: If I autoload my custom library (add to config/autoload.php)... IT WORKS!

What's the mistake here?

PS: I also tried this, from the same view, without luck

Code:
$CI =& get_instance();
$CI->load->library('mymsg');



Strange behaviour with custom library, my mistake? - El Forum - 04-24-2012

[eluser]Glazz[/eluser]
Hmm with that message i guess that the library is not loading..

I tested loading a library in one view and it worked properly, but i recomend you to load libraries/models/etc.. in your controller..

Try loading your library in your controller and see if it works


Strange behaviour with custom library, my mistake? - El Forum - 04-24-2012

[eluser]CARP[/eluser]
I loaded the library within the controller, and works, but I know I'll need sometime to load this custom library from a view.
I thought loading libraries from views would work, but seems I missed some part in the manual Tongue


Strange behaviour with custom library, my mistake? - El Forum - 04-24-2012

[eluser]Glazz[/eluser]
Well, like i said, i tried to load a library from a view and it worked, don't know what happened when you tried it, but everyone recomend to load libraries on controllers, or even using the autoloader =)




Strange behaviour with custom library, my mistake? - El Forum - 04-24-2012

[eluser]Aken[/eluser]
I just tried to load a library in a view using the latest dev version of CodeIgniter and it did not work properly. I'm gonna look into this and try and see why.

Edit:

So inside a view, the $this variable is assigned to the CI_Loader class, not the super object. If you load a library in the view, the library loads properly, but is not accessible to the scope of CI_Loader.

Like you, I was under the impression that $this within a view offered global access, but it doesn't. Maybe that can be amended to the user guide if it hasn't been yet, but CI is functioning as it should by throwing errors.

If you really want to do it this way, you should use the $ci =& get_instance() method. However, as others have mentioned, loading libraries and such is best done in the controller, since that is a more appropriate MVC style.