Symfony + Doctrine: Single mapping file for multiple entities (global mapping)


Doctrine lets you define database ORM mapping using YAML, XML or PHP Annotations. I wanted to put all my mapping information in a single file, in order to streamline updating for one or two of my own reasons.

I found this snippet:

$namespaces = array(
'/path/to/files1' => 'MyProject\Entities',
'/path/to/files2' => 'OtherProject\Entities'
$driver = new \Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver($namespaces);
$driver->setGlobalBasename('global'); // global.orm.yml

Which is nice but we are not implementing the Doctrine driver ourselves when using Symfony 2.1, so I did a quick search for setGlobalBaseName in the Symfony Doctrine ODM bundle and found that it was setting the global basename to mapping and not global.

So, if you wish to have a global YAML mapping definition file, you can create one like:


The mapping.orm.yml file should look something like this:

  type: entity
  tableName: employees
    ref: { type: char(6), primary: true, notnull: true }
    first_name:  { type: string(50), notnull: true }
    last_name:  { type: string(50), notnull: true }
    birthdate:    { type: timestamp, notnull: true }
    hiredate:     { type: timestamp, notnull: true }
    email:         { type: string(100), notnull: true }
        targetEntity: Company
          name: company_id
          referencedColumnName: id
  type: entity
  tableName: companies
      type: char(6)
      primary: true
      notnull: true
      name:  { type: string(50), notnull: true }

Then, we can generate the model classes (or entities) using: $ php app/console doctrine:generate:entities TestBundle

This makes the Employee.php and Company.php in: /www/src/Acme/TestBundle/Entity/

So there you have it, setting up a global YAML mapping file, and generating entity classes from it!

Hope this helps someone out there.