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.
<?php
$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:
/www/src/Acme/TestBundle/Resources/config/doctrine/mapping.orm.yml
The mapping.orm.yml file should look something like this:
Acme\TestBundle\Entity\Employee:
type: entity
tableName: employees
fields:
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 }
oneToOne:
company:
targetEntity: Company
joinColumn:
name: company_id
referencedColumnName: id
Acme\TestBundle\Entity\Company:
type: entity
tableName: companies
fields:
ref:
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.