Highly Opinionated Thoughts on Programming

by Elnur Abdurrakhimov


How to Enable the Underscore Naming Strategy for Doctrine ORM in Symfony

Mar 6, 2014


In PHP, it’s idiomatic to use camel case when naming things:

1
2
3
4
5
class SuperUser
{
    private $firstName; 
    private $lastName;
}

In SQL, it’s idiomatic to use underscores:

1
2
3
4
5
6
 
CREATE TABLE super_user
(
    first_name varchar,
    last_name varchar
);

By default, the Doctrine ORM uses the PHP names verbatim, so it will look for a SuperUser table with firstName and lastName columns when mapping to the class given above. Since I prefer to respect idioms of each tool, I don’t like the idea of bending one tool to the idioms of another.

Of course, you could solve that problem explicitly and manually:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Column;

/**
 * @Table("super_user")
 */
class SuperUser
{
    /**
     * @Column("first_name")
     */
    private $firstName;

    /**
     * @Column("last_name")
     */
    private $lastName;
}

But I don’t like the idea of doing all this manually. Meet the underscore naming strategy; it does all that stuff for you automatically. To enable it, set the naming strategy in the ORM configuration in config.yml:

1
2
3
doctrine:
    orm:
        naming_strategy: doctrine.orm.naming_strategy.underscore

Note: You need Doctrine ORM 2.3+ for this to work.



© Elnur Abdurrakhimov