codeigniter - Extending CI_Model for use with report database -
i trying add separate report database application extending ci_model , setting correct database use based on if database defined. report database replicated version of regular database performance reasons.
is proper way?
in application/core/my_model:
<?php class my_model extends ci_model { function __construct() { parent::__construct(); include apppath.'config/database.php'; //if have reporting database load , use reporting functions if (isset($db['reports'])) { $this->report_db = $this->load->database('reports', true); } else { $this->report_db = $this->load->database('default', true); } } } ?>
you can use both of databases within code. have define in config/database.php
database.php
$active_group = 'default'; $active_record = true; $db['default']['hostname'] = 'localhost'; $db['default']['username'] = 'username'; $db['default']['password'] = 'password'; $db['default']['database'] = 'database1'; $db['default']['dbdriver'] = 'mysqli'; $db['default']['dbprefix'] = ''; $db['default']['pconnect'] = true; $db['default']['db_debug'] = true; $db['default']['cache_on'] = false; $db['default']['cachedir'] = ''; $db['default']['char_set'] = 'utf8'; $db['default']['dbcollat'] = 'utf8_general_ci'; $db['default']['swap_pre'] = ''; $db['default']['autoinit'] = true; $db['default']['stricton'] = false; $db['reports']['hostname'] = 'localhost'; $db['reports']['username'] = 'username'; $db['reports']['password'] = 'password'; $db['reports']['database'] = 'database2'; $db['reports']['dbdriver'] = 'mysqli'; $db['reports']['dbprefix'] = ''; $db['reports']['pconnect'] = true; $db['reports']['db_debug'] = true; $db['reports']['cache_on'] = false; $db['reports']['cachedir'] = ''; $db['reports']['char_set'] = 'utf8'; $db['reports']['dbcollat'] = 'utf8_general_ci'; $db['reports']['swap_pre'] = ''; $db['reports']['autoinit'] = true; $db['reports']['stricton'] = false;
reports_model.php
<?php class reports_model extends ci_model { public function __construct() { parent::__construct(); $this->db_reports = $this->load->database('reports', true); } public function reports_list() { $this->db_reports->get('some_table'); } }
other_model.php
<?php class other_model extends ci_model { public function __construct() { parent::__construct(); } public function xyz() { $this->db->get('some_table'); } }
explanation:
since have defined default
active group, whatever database
have defined in default group
, can use following in model -
$this->db->get('some_table'); // defined
and sine have other databases can have group of them. have defined them in reports group
. have add _reports
after db
-
$this->db_reports->get('some_table');
Comments
Post a Comment