Skip to content

How to Use Doctrine DBAL

Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.1 (the current stable version).

Note

This article is about the Doctrine DBAL. Typically, you'll work with the higher level Doctrine ORM layer, which simply uses the DBAL behind the scenes to actually communicate with the database. To read more about the Doctrine ORM, see "Databases and the Doctrine ORM".

The Doctrine Database Abstraction Layer (DBAL) is an abstraction layer that sits on top of PDO and offers an intuitive and flexible API for communicating with the most popular relational databases. In other words, the DBAL library makes it easy to execute queries and perform other database actions.

Tip

Read the official Doctrine DBAL Documentation to learn all the details and capabilities of Doctrine's DBAL library.

To get started, configure the database connection parameters:

1
2
3
4
5
6
7
8
9
# app/config/config.yml
doctrine:
    dbal:
        driver:   pdo_mysql
        dbname:   Symfony
        user:     root
        password: null
        charset:  UTF8
        server_version: 5.6

For full DBAL configuration options, or to learn how to configure multiple connections, see Doctrine Configuration Reference (DoctrineBundle).

You can then access the Doctrine DBAL connection by accessing the database_connection service:

1
2
3
4
5
6
7
8
9
10
11
use Doctrine\DBAL\Driver\Connection;

class UserController extends Controller
{
    public function indexAction(Connection $connection)
    {
        $users = $connection->fetchAll('SELECT * FROM users');

        // ...
    }
}

Registering custom Mapping Types

You can register custom mapping types through Symfony's configuration. They will be added to all configured connections. For more information on custom mapping types, read Doctrine's Custom Mapping Types section of their documentation.

1
2
3
4
5
6
# app/config/config.yml
doctrine:
    dbal:
        types:
            custom_first:  AppBundle\Type\CustomFirst
            custom_second: AppBundle\Type\CustomSecond

Registering custom Mapping Types in the SchemaTool

The SchemaTool is used to inspect the database to compare the schema. To achieve this task, it needs to know which mapping type needs to be used for each database types. Registering new ones can be done through the configuration.

Now, map the ENUM type (not supported by DBAL by default) to the string mapping type:

1
2
3
4
5
# app/config/config.yml
doctrine:
    dbal:
        mapping_types:
            enum: string
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version