Tuesday, December 1, 2009

Connect to a database

In this example, we implement a connection to a database.

Components used in this example
Implementation of the connection

class MyDbConnection
The connection process
  • We get the connection method from the GET request.
  • We connect with the database adapter, the factory method, or the configuration.
  • We get the configuration details.

    public function process()
// We get the connection method from the GET request.
list($method) = $this->_getParameters();

// We connect with the database adapter, the factory method, or the configuration.
switch ($method) {
'Zend_Db Adapter':
$db = new Zend_Db_Adapter_Pdo_Sqlite(array('dbname' => ':memory:'));

'Zend_Db Factory':
$db Zend_Db::factory('Pdo_Sqlite', array('dbname' => ':memory:'));

$config = new Zend_Config(array(
'database' => array(
'adapter' => 'Pdo_Sqlite',
'params'  => array('dbname' => ':memory:')
$db Zend_Db::factory($config->database);

// We get the configuration details.
$message = isset($db)? $db->getConfig() : array();

        return array(
Extraction of the parameters from the GET request

    private function _getParameters()
$method = isset($_GET['method'])? $_GET['method'] : '';

        return array(


No comments:

Post a Comment