Default Fetch Mode for Doctrine DBAL

After using Doctrine DBAL for a while, I’ve realized that I always fetch an object. There may be some good reasons to fetch an array, but I never do. The documentation for Doctrine DBAL is nice, in fact I think it is wonderful how basic usage is explained, but not everything is covered. After digging around in the code, I found out how to set a default fetch mode so I don’t have to do it in all my queries. You can do it right as you make your connection to the database.

$connectionParams = array(
  'dbname'   => 'mydb',
  'user'     => 'user',
  'password' => 'secret',
  'host'     => 'localhost',
  'driver'   => 'pdo_mysql'

$conn = \\Doctrine\\DBAL\\DriverManager::getConnection( $connectionParams );

$conn->setFetchMode( \\PDO::FETCH_OBJ );

The last line in the example above is setting the fetch mode to default to object.

One thought on “Default Fetch Mode for Doctrine DBAL”

Comments are closed.