我不想自动加载Settings_model (在autoload.php中),因为该模型会打开一个新的数据库连接。它没有什么问题,但它为我创建的每个新对象(我不想要)打开一个新的数据库连接。
Settings_model的代码段:
class Settings_model extends CI_Model {
public static $db_config = array();
public function __construct() {
parent::__construct();
$this->_load_settings();
}
/**
*
* _load_settings: load the settings from database
*
*
*/
protected function _load_settings() {
$this->load->library('cache');
$data = $this->cache->get('settings');
if (empty($data)) {
$this->db->select('login_enabled, register_enabled, install_enabled, members_per_page, admin_email, home_page, active_theme,
login_attempts, recaptcha_theme, email_protocol, sendmail_path, smtp_host, smtp_port, smtp_user, smtp_pass, site_title, cookie_expires,
password_link_expires, activation_link_expires, disable_all, site_disabled_text, remember_me_enabled, recaptcha_enabled');
$this->db->from('settings');
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1) {
$row = $query->row();
self::$db_config['login_enabled'] = $row->login_enabled;
self::$db_config['registration_enabled'] = $row->register_enabled;
self::$db_config['install_enabled'] = $row->install_enabled;
etc...
MY_Controller看起来像这样:
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
if (Settings_model::$db_config['disable_all'] == 1 && $this->session->userdata('role_id') != 1 && $this->uri->segment(2) != "login") {
$this->session->sess_destroy();
redirect('site_offline');
}
所以基本上当我创建新对象时:
$x = new Object()
**MY_Controller** is called.
Settings_model is called and db-connection are made
(because $this->load_settings() are called in the constructor).
如何正确使用Settings_model而无需在autoload.php中自动加载?
是的我可以在每个控制器中使用类似$this->load->model('system/settings_model')
的内容,但在某些配置文件中,它会获取如下值:
$config['recaptcha'] = array(
'public'=>'',
'private'=>'',
'RECAPTCHA_API_SERVER' =>'http://www.google.com/recaptcha/api',
'RECAPTCHA_API_SECURE_SERVER'=>'https://www.google.com/recaptcha/api',
'RECAPTCHA_VERIFY_SERVER' =>'www.google.com',
'RECAPTCHA_SIGNUP_URL' => 'https://www.google.com/recaptcha/admin/create',
'theme' => Settings_model::$db_config['recaptcha_theme']
);
很难解释这一点,但可以随意质疑是否有不明确的事情。