基本上,我拥有的是:
class Database extends CI_Model
{
function __construct()
{
parent::__construct();
}
function connect($connection_infos)
{
$db = @new mysqli($connection_infos['host'], $connection_infos['username'],
$connection_infos['password'], $connection_infos['database']);
if (mysqli_connect_errno())
return FALSE;
else
return TRUE;
}
}
该模型加载在控制器的功能中:
class Management extends CI_Controller
{
static $dbs = array(
'ref' => array(
'connected' => FALSE,
),
'dest' => array(
'connected' => FALSE,
)
);
function connection()
{
$this->load->library('form_validation');
$data = array();
$this->form_validation->set_rules('host', 'Hostname', 'required');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('database', 'Database', 'required');
if (!$this->form_validation->run()) {
$data['dbs'] = self::$dbs;
} else {
$this->load->model('database'); // Here I load the model
$connection_infos = array(
'host' => $this->input->post('host'),
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'database' => $this->input->post('database'),
);
if ($this->database->connect($connection_infos)) {
self::$dbs['ref']['connected'] = TRUE;
$data['dbs'] = self::$dbs;
}
}
$this->load->view('dashboard', $data);
}
}
以下是我所做的:
在我视图中的表单验证中,我从控制器中调用函数connection
。此函数加载Database
模型,并调用该模型的函数connect
。
我的问题是:如果我想让我的模型中的其他函数发出其他人的请求,我会被迫每次打开一个连接吗?如果是,我如何"存储"连接凭据?
谢谢!
根据我所看到的,您需要访问CI文档,并读取数据库库上的批次。
除了教程中介绍的基本语法/语义之外,名为"Database"的模型是不合逻辑的,并且不是一个很好的命名选择。在CodeIgniter的范围内,您应该尝试使模型只与一个数据库表相关。
至于实际的数据库连接,它在CI_Model类中作为成员对象$db
自动处理。我建议阅读CI.中关于模型和数据库连接的文档
因此,当您正确设置了所有内容时,加载一个正确编码的模型将在模型中为您提供一个自动的数据库连接,该连接可以随时重用。