如何检查Zend_Db_Adapter_Pdo_Mysql对象是否连接到数据库

时间:2011-11-15 14:59:47

标签: php database-connection zend-db zend-framework

正在开发一个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();
    }

}

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);

2 个答案:

答案 0 :(得分:4)

根据Zend_Db_Adapter documentation,您可能在调用适配器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
}

希望有所帮助,

答案 1 :(得分:1)

我想知道你为什么需要这个。

如果您使用标准ZF引导,Zend_Application_Bootstrap_Bootstrap将为您管理数据库连接。

如果没有有效连接,Zend_Db::factory会自动为您创建一个。此外,如果您的数据库设置保持不变并且已经存在活动的Zend_Db对象,则Zend_Db_Adapter将不会创建另一个连接

你需要在application.ini中有一个db连接部分,bootstrap将为你处理一切。

resources.db.adapter            = "pdo_mysqli"
resources.db.params.host        = "localhost"
resources.db.params.dbname      = "db"
resources.db.params.username    = "user"
resources.db.params.password    = "pass"