How to use Symfony with existing database

I recently had to start a Symfony2 project using an existing database. Here is a rough guide on how it is done.

Firstly you have to update your app/config/parameter.ini to your existing database:

[code lang=”bash”][parameters]
database_driver=”pdo_mysql”
database_host=”127.0.0.1″
database_port=””
database_name=”gladlycode”
database_user=”root”
database_password=”root”
mailer_transport=”smtp”
mailer_host=”localhost”
mailer_user=””
mailer_password=””
locale=”en”
secret=”0bdc03a00514e9c1595219d165115d532″
[/code]

My bundle is named GladlyCodeBundle, you will have to rename this. Based on this I do a map of existing database tables into XML format, note that the em dash is 2 dashes due to conversion by WordPress:

[code lang=”bash”]php app/console doctrine:mapping:convert xml ./src/Gladly/CodeBundle/Resources/config/doctrine/metadata/orm –from-database –force[/code]

You need to change the ‘Gladly/CodeBundle’ part to fit your project as the next step will look to import from the default location.

If you get any errors of this sort:

[code lang=”bash”]PHP Fatal error: Call to a member function getColumns() on a non-object in /Users/kahwee/projects/gladlycode/vendor/doctrine/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php on line 133
PHP Stack trace:
PHP 1. {main}() /Users/kahwee/projects/gladlycode/app/console:0
PHP 2. SymfonyComponentConsoleApplication->run() /Users/kahwee/projects/gladlycode/app/console:22
…[/code]

It could be due to one of your tables not having a primary key. Just assign it the appropriate primary to continue with the import process.

Then I import them with annotations:

[code lang=”bash”]php app/console doctrine:mapping:import GladlyCodeBundle annotation[/code]

Finally I regenerate them into entities:

[code lang=”bash”]php app/console doctrine:generate:entities GladlyCodeBundle[/code]

And that’s it. Everything is imported.

Leave a Reply

Your email address will not be published. Required fields are marked *