无法想出这个:
在DB_driver.php
(核心系统/数据库)
这是init函数的开始...
/**
* Initialize Database Settings
*
* @return bool
*/
public function initialize()
{
/* If an established connection is available, then there's
* no need to connect and select the database.
*
* Depending on the database driver, conn_id can be either
* boolean TRUE, a resource or an object.
*/
if ($this->conn_id)
{
return TRUE;
}
// ----------------------------------------------------------------
// Connect to the database and set the connection ID
$this->conn_id = $this->db_connect($this->pconnect);
initialize()
被称为wihtin CI_Controller
所以在创建新对象时,例如:
$x = new PartyPooper();
$y = new PartyPooper();
initialize()
中的 DB_driver
被调用两次。没有什么奇怪的,但我希望在第二次创建$this->conn_id
对象(PartyPooper()
)时设置$y
?
什么时候“已建立的联系”应该是真的? (在示例中,当应该只有一个时,会建立两个数据库连接?)
我在开发分支中使用最新的数据库驱动程序:https://github.com/EllisLab/CodeIgniter/tree/develop/system/database
我正在使用具有持久连接的mysqli-driver。
更新
我不是一个搞乱核心文件的粉丝,但我无法在这里找到另一种解决方案。请告诉我是否有更好的方法来实现我想做的事情。
我想出了这个代码(使用会话来处理存储和检查现有数据库连接(“subdriver” - 对象。(在我的情况下是mysqli对象)):
public function initialize()
{
/* If an established connection is available, then there's
* no need to connect and select the database.
*
* Depending on the database driver, conn_id can be either
* boolean TRUE, a resource or an object.
*/
if ($this->conn_id) {
return TRUE;
}
$conn_session_id_name = 'dbsession_conn';
if (isset($_SESSION[$conn_session_id_name])) {
$sess = $_SESSION[$conn_session_id_name];
// Set connection id object or resourse and return true
// because no more connecting has to be done
if (is_object($sess) || is_resource($sess)) {
$this->conn_id = $sess;
return TRUE;
}
}
// Connect to the database and set the connection ID
$this->conn_id = $this->db_connect($this->pconnect);
// Store conn object or resource etc into session
if (is_object($this->conn_id) || is_resource($this->conn_id)) {
$_SESSION[$conn_session_id_name] = $this->conn_id;
}
// No connection resource? Check if there is a failover else throw an error
if ( ! $this->conn_id)
{
//rest of code as before...
我的应用程序极快得多,因为它使用了一个连接而不是大约60个。
但我原来的问题仍然存在:
在initialize()
函数中,这应该是什么时候?
if ($this->conn_id) {
return TRUE;
}
(我在更改代码时没有将其删除,因为我认为它有一些目的 - 但即使我无法弄明白哪个)
UPDAtE2 - 澄清:
在模型中,我有一个应该返回PartyPooper对象的db select语句:
例如。 $res = $q->result('PartyPooper');
这个PartyPooper是一个控制器,存储有关人的信息,如姓名,年份,生日等,但它也处理同一对象内的信息计算等内容。
class PartyPooper extends CI_Controller { .... }
但正如我从下面的评论中理解的那样,我应该这样做吗?
class PartyPooper extends CI_Controller { .... }
class PartyPooperObject { .... } //Store information about people in this object
例如。 $res = $q->result('PartyPooperObject');
答案 0 :(得分:1)
这段代码
if ($this->conn_id) {
return TRUE;
}
只是确保initialize
方法仅被称为一次 每个对象。
如果已经在当前对象上调用它,则不能再执行它。