ZF2 has some big game changers for database connectivity. The Zend_Db_Table is no longer, and has since been replaced by the new TableGateway. What I’m finding so far is that the default database adapter is no longer used, or I’m unsure how to initialize it, so that you must pass the database adapter into each table you use. This can get crazy, but if you develop a wrapper for your database connections it isn’t so bad.
// somewhere in your db model, which must implement ZendServiceManagerServiceManagerAwareInterface $this->adapter = $this->getServiceManager()->get('db'); $table = new TableGateway("my_db_table", $this->adapter);
The database setup is similar to the original application.ini setup in ZF1:
<?php // database loading informaiton return array( 'service_manager' => array( 'factories' => array( 'ZendDbAdapterAdapter' => 'ZendDbAdapterAdapterServiceFactory', ), 'aliases' => array( 'db' => 'ZendDbAdapterAdapter', ), ), 'db' => array( 'driver' => 'pdo', 'pdodriver' => 'mysql', 'host' => 'localhost', 'database' => 'db_name', 'username' => 'db_user', 'password' => 'db_pass', 'driver_options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"), ), );
Another fun thing that I found was actually easier than in ZF1 was to switch databases while keeping the same exact credentials:
$serviceManager = $this->getServiceManager(); $databaseAdapter = $serviceManager->get('db'); $dbParams = $databaseAdapter->getDriver()->getConnection()->getConnectionParameters(); $dbParams['database'] = $siteDetail['database_location']; /** * Edited 10/15 - found a defect with trying to set the connection parameters, * found that it worked 100% of the time when you simply returned a new instance * of the adapter. */ return new Adapter($dbParams);