Using database class from functions within custom library?

#1
[eluser]x_dde_x[/eluser]
Hey Codeigniter helpers,

I'm in the process of converting all of my old sites to codeigniter (figure it's good practice and a great education on codeigniter), and I'm wondering if I'm going about this the right way.

Here's the issue: I have a custom Library that a lot of my controllers will use to render passed xml strings into dynamic charts. There are a few database calls that the library uses to load dates that appear in the table. However, I cannot get the functions to use CI's database functions unless I instantiate the CI instance and database from each and every function.

Here's the code, maybe you can quickly tell where I've gone wrong (or if I need to create a custom Model to pull database calls, and separate that from the Library).
Code:
class Chart {
    var $CI;      
    function Chart()
        {
        $CI =& get_instance();
        $CI->load->database();    
        $CI->load->helper('url');
        $CI->load->library('session');
        $CI->config->item('base_url');
    }

      function render_date_range($interval,$timeframe)
     {
     $sql=$CI->db->query("text of query");
     }

trying to call the render date function will fail with: Undefined variable: CI unless I add $CI =& get_instance(); and $CI->load->database(); from each and every function...

#2
[eluser]sophistry[/eluser]
it looks like it should work, don't have any good ideas on why it wouldn't. that is standard code for getting external libs to talk to CI internals. but, note that if you are on PHP4 the manual has a nice big red and pink warning for you about get_instance() in constructors.

Quote:Also, please note: If you are running PHP 4 it's usually best to avoid calling get_instance() from within your class constructors. PHP 4 has trouble referencing the CI super object within application constructors since objects do not exist until the class is fully instantiated.

anyhow, thought you might like to have a look at this if you are re-building sites in CI. it makes it a lot easier to progressively migrate into CI rather than having to build everything all at once.

http://codeigniter.com/wiki/site_migrate/

#3
[eluser]m4rw3r[/eluser]
I've noticed that you've forgot the $this-> which precedes the property names, so "$CI" should be "$this->CI".

#4
[eluser]x_dde_x[/eluser]
Ah! It's always the simplest things that will get you!

I needed to use $this->CI->db->query()

All is right with the world, thank you m4rw3r!


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.