Mar*_*irs 3 php database-connection zend-framework zend-db
我正在开发一个Zend应用程序,在该应用程序中,我需要保留数据库对象的单个实例,并在当前实例断开连接的情况下重新连接。这是代码:
class Resource_PdoMysql extends Zend_Application_Resource_ResourceAbstract
{
const KEY = 'PDO_MYSQL';
private static function connect()
{
$connParams = array("host" => host,
"port" => 'port',
"username" => 'username',
"password" => 'password',
"dbname" => 'dbname');
$db = new Zend_Db_Adapter_Pdo_Mysql($connParams);
return $db;
}
public static function getConnection()
{
if (!Zend_Registry::isRegistered(self::KEY))
{
$db = self::connect();
Zend_Registry::set(self::KEY, $db);
}
return Zend_Registry::get(self::KEY);
}
public static function reconnect()
{
$db = self::connect();
Zend_Registry::set(self::KEY, $db);
}
public function init()
{
return self::getConnection();
}
Run Code Online (Sandbox Code Playgroud)
}
Am using $db like this
$db = Resource_PdoMysql::getConnection();
// <Here I need to check if the connection is open before proceeding>
$db->insert('table', $data);
Run Code Online (Sandbox Code Playgroud)
根据Zend_Db_Adapter文档,调用适配器getConnection()方法后可能会捕获异常。这是该示例的复制粘贴摘录:
try {
$db = Zend_Db::factory('Pdo_Mysql', $parameters);
$db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
// perhaps a failed login credential, or perhaps the RDBMS is not running
} catch (Zend_Exception $e) {
// perhaps factory() failed to load the specified Adapter class
}
Run Code Online (Sandbox Code Playgroud)
希望能有所帮助,
| 归档时间: |
|
| 查看次数: |
6330 次 |
| 最近记录: |