Thursday, April 09, 2015

Some tips for Doctrine2 entities' generation from an existing database

So I began working on Symfony2 framework, i had to map an existing database with Doctrine2. First of all, keep in mind  that Doctrine2 gives its best for creating a schema, not for generating an object model from an existing one.

It's therefore important to "prepare" your database before generation unless you'll get an approximative model...
You must define a Primary Key on each table of your DB. It seems obvious but Doctrine2 will fail otherwise...

 Composite primary keys including only foreign keys is not yet fully supported by Doctrine2 (see documentation). Think about adding an auto-increment integer as PK and apply a UNIQUE index on foreign keys from old composite PK.

Natively, Doctrine2 doesn't natively resolve BIT, BINARY, VARBINARY, TINYBLOB, MEDIUMBLOB, BLOB, LONGBLOB, ENUM, SET, GEOMETRY, POINT, MULTIPOINT, LINESTRING, MULTILINESTRING, POLYGON and MULTIPOLYGON.

Important : Doctrine2 converts SQL type TINYINT to PHP type boolean. Use at least a SMALLINT if you want to mean an integer.

Doctrine automatically assignes IDs with generator (PHP equivalent to auto_increment) but it does it for all types of simple Primary Keys, even strings and foreign keys...

When you're satisfied of your schema, you can generate the metadatas with the command CLI interface :


First step : convert your mapping

$ php app/console doctrine:mapping:convert xml ./src/Xxx/YourBundle/Resources/config/doctrine/metadata/orm --from-database --force

Note : I prefer XML for mapping => DB model is independant from code. Use annotations if you create your schema from Doctrine Entities, not for "reverse engineering" (used term by Doctrine documentation).

You'll get some .orm.xml files describing your database model in ./src/Xxx/YourBundle/Resources/config/doctrine/metadata/orm. These files don't resolve namespaces of your application, that's why step 2 is needed.

Second step : import your mapping

$ php app/console doctrine:mapping:import XxxYourBundle xml

Some new .orm.xml files describing your database model in ./src/Xxx/YourBundle/Resources/config/doctrine. These files resolve namespaces of your application. Don't delete files generated during first step, you still need them to generate entities !

Third step : generate entities

$ php app/console doctrine:generate:entities XxxYourBundle

Entities PHP files are generated in ./src/Xxx/YourBundle/Entity.
Post a Comment

How to get the IP address of the docker host from inside a docker container

/sbin/ip route|awk '/default/ { print $3 }'