我正在使用zend框架。目前我每次需要使用db时都会继续并连接到DB:
function connect()
{
$connParams = array(
"host" => $host,
"port" => $port,
"username" => $username,
"password" => $password,
"dbname" => $dbname
);
$db = new Zend_Db_Adapter_Pdo_Mysql($connParams);
return $db
}
所以我每次需要使用db
时都会调用connect()函数我的问题是......假设我想在我的网站中重复使用$ db,并且只在网站加载的最初阶段连接一次,然后在网站发送给用户之前关闭连接,那会是什么是最好的做法来实现这一目标?
Zend中的哪个文件应该保存$ db,我应该使用什么方法来保存它(全局变量?),以及我应该关闭哪个文件?
答案 0 :(得分:2)
如果您使用的是默认项目结构(包含应用程序,库,测试和公用文件夹),则应使用 application / configs / application.ini
示例application.ini:
[production]
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "testuser"
resources.db.params.dbname = "testdb"
resources.db.params.password = "testpasswd"
resources.db.isDefaultTableAdapter = true
通过这种方式,zend框架将自动打开和关闭与数据库的连接,您可以使用Zend_Db_Table或Zend_Db_Table_Abstract类轻松查询表,例如,检索给定SSN的学生数据,您可以编写模型( application / models / Student.php )看起来像这样:
<?php
class Model_Student extends Zend_Db_Table_Abstract
{
protected $_name = "student";
public function fetchRowsBySSN($ssn)
{
$select = $this->select();
$select->where('ssn = ?', $ssn);
return $this->fetchRow($select)->toArray();
}
}
正如您所看到的,无需打开/关闭连接,您将获得一个包含学生记录的字段和值的关联数组。
答案 1 :(得分:1)
您最好的方法可能是将所有数据库连接代码移到单独的class
中,您可以在其中设置static $db
var。
protected static $_db;
public static function connect()
{
if (self::$_db == null) {
$config = Zend_Config_Xml(); // whatever you'd use
self::$_db = Zend_Db::factory($config->database);
self::$_db->setFetchMode(Zend_Db::FETCH_OBJ);
self::$_db->query('SET NAMES UTF8');
Zend_Db_Table::setDefaultAdapter(self::$_db); // optional
}
return self::$_db;
}
public static function close()
{
if (self::$_db != null) {
self::$_db->closeConnection();
}
}
据Zend说:
通常没有必要关闭数据库连接。 PHP会自动清理所有资源并结束请求。数据库扩展旨在关闭连接,因为清理了对资源对象的引用。
但是,如果您有一个启动许多数据库连接的长时间PHP脚本,则可能需要关闭连接,以避免耗尽RDBMS服务器的容量。您可以使用Adapter的closeConnection()方法显式关闭底层数据库连接。