2

I want to access database functions in extending libraries.

class My_Router extends CI_Router {

    public function __construct()
    {
        parent::__construct();
    }

    function _set_routing()
    {
        .....
        ....
        $query=$this->db->get('custome_routes');
        $custom_routes=$query->result_array();
        ....

    }
 }

I tried below also

 $CI =& get_instance();
    $query=$CI->db->get('custome_routes');
    $custom_routes=$query->result_array();

But it doesn't work.

Help me....

Thanks in advance, Logan

Logan
  • 1,682
  • 4
  • 21
  • 35

2 Answers2

3

Unfortunately you can't do that, because the loading order of the framework, and since the routing information is used to decide what controller class to load, and the return value of get_instance() is that controller instance.

You can try using CI's built in class by require ing the system/DB.php and use the DB() function to get an instance of the db class.

public function _set_routing(){
    require_once BASEPATH.'database/DB.php';
    $db = DB('default', true); // you can set the database.php config's group, or a full DSN string here
    $custom_routes = $db->get('custome_routes')->result_array();
}

Or you could make a CI independent db connection in your subclass, for this one "get the full table" query this shouldn't be hard. You should be able to include the CI database config file and use it's values without problems (watch out for environments).

complex857
  • 20,425
  • 6
  • 51
  • 54
  • it getting error "Fatal error: Class 'CI_Controller' not found" – Logan Aug 25 '12 at 17:39
  • @complex857 Use `BASEPATH` instead of `SYSDIR`. – ADev Aug 25 '12 at 18:09
  • Strange, i don't see anything in your question that should does that, and my test setup worked fine. I'm only guessing but maybe your implementation of `_set_routing()` is not functioning as the original one. (the one in the answer is obviously not the full method.) – complex857 Aug 25 '12 at 18:13
1

Just load database from instance ( $CI->load->database(); )

$CI =& get_instance();
$CI->load->database();

$query=$CI->db->get('custome_routes');
$custom_routes=$query->result_array();

EDIT: This just work for libraries and does not work for core classes.

ADev
  • 686
  • 4
  • 13
  • 1
    That won't work since when the call to [`_set_routing()`](https://github.com/EllisLab/CodeIgniter/blob/develop/system/core/CodeIgniter.php#L164) issued before [`get_instance()`](https://github.com/EllisLab/CodeIgniter/blob/develop/system/core/CodeIgniter.php#L227) is defined. – complex857 Aug 25 '12 at 16:54
  • Yes, that's not work for core classes, but the problem is `core/Controller.php` included after router loading. – ADev Aug 25 '12 at 17:51