Am developing a Zend application where i need to keep a single instance of the database object and reconnect if the current instance is somehow disconnected. Here is the code:
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);
According to the Zend_Db_Adapter
documentation, you might catch an exception after calling the adapter getConnection()
method. This is the copy-pasted excerpt from the example:
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
}
Hope that helps,
I wonder why you need this.
if you're using the standard ZF bootstrapping, the Zend_Application_Bootstrap_Bootstrap
will manage the database connections for you.
If there are no active connection, the Zend_Db::factory
will create one for you automatically. also, Zend_Db
won't create another connection if your db settings stays the same and there's already an active Zend_Db_Adapter
object
you need to have a section in your application.ini with the db connection, and the bootstrap will handle everything for you.
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"