CodeIgniter Forums
Can't use $this->load->database() anywhere? - 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: Can't use $this->load->database() anywhere? (/thread-17610.html)



Can't use $this->load->database() anywhere? - El Forum - 04-09-2009

[eluser]Unknown[/eluser]
Hi,

I'm using CI 1.7 with codecrafter to generate the scaffolding. This makes me realize the i can't use $this->load->database() anywhere, only in the constructor, otherwise no connection is created.
What could be happening? am i doing something wrong?

I think that using $this->load->database() in any function should work because the codecrafter use it a lot.

any ideas?

thanks


Can't use $this->load->database() anywhere? - El Forum - 04-09-2009

[eluser]TheFuzzy0ne[/eluser]
Welcome to the CodeIgniter forums!

It is available:
Code:
$CI =& get_instance();
$CI->load->database();



Can't use $this->load->database() anywhere? - El Forum - 04-09-2009

[eluser]Unknown[/eluser]
So if i add the line $CI = &get;_instance() before and use $CI->load.... i could call any of them, anywhere in the code...

e.g.
CI= get instance()
CI->load->somemodel | somelibrary | somehelper ...

mmm... not documented? or i am a lazy reader haha


Can't use $this->load->database() anywhere? - El Forum - 04-09-2009

[eluser]jedd[/eluser]
[quote author="victorpy" date="1239340320"]So if i add the line $CI = &get;_instance() before and use $CI->load.... i could call any of them, anywhere in the code... [/quote]

In effect, yes. Note that if you are using a database, there's a lot to be said for loading the database class in config/autoload.cfg rather than in each function (or indeed in each controller).

Quote:mmm... not documented? or i am a lazy reader haha

The CI User Manual maintains brevity, but contains [url="http://ellislab.com/codeigniter/user-guide/general/creating_libraries.html"]everything you need[/url].


Can't use $this->load->database() anywhere? - El Forum - 04-09-2009

[eluser]Tom Schlick[/eluser]
but for things such as libraries you should probably do the following so you dont have to use get_instance() in every single function...
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class WhateverClassNameYouGiveIt
{
    
    var $CI;
    
    function __construct()
    {
        $this->CI =& get_instance();
    }
    
    function whatever()
    {
        $this->CI->whatever_library->some_function_to_do_something();
    }
}