Skip to content

Instantly share code, notes, and snippets.

@jamesstacyjones
Last active December 23, 2015 13:59
Show Gist options
  • Save jamesstacyjones/6645309 to your computer and use it in GitHub Desktop.
Save jamesstacyjones/6645309 to your computer and use it in GitHub Desktop.
symfony2 - create database entities based on database schema.

From terminal to run these commands. As there are 3 commands to run in order to get Symfony2 to recognize the database as entities.

Step 1: Import database into Bundle and create yaml files. [ --em=dev ] Used to recognize the database to import. In order to do this the database configuration files need to be set up with parameters.yml and config.yml

./app/console doctrine:mapping:import --em=dbname BundleName yml

Step 2: Create annotations of the yaml files and place into into Entity folder.

[note] Make sure that if you are using ./app/console that you use ./src if you are in the app folder and use ./console then you will need to use ../src

./app/console doctrine:mapping:convert --em=dbname annotation ./src

Step 3: Add the getters and setters to the annotation entities.

[note] If it is a large database then you mind as well go see a movie as it is going to take awhile.

./app/console doctrine:generate:entities BundleName --no-backup

That is it, except that I was not happy that the yaml files didn't create a entity repository at the same time as the entity was being created therefore I wrote a script to create this. I placed it in the root folder. But one can place it anywhere and modify paths accordingly. After you modify the yaml files then you get to go back and do annotate and generate.

<?php
// add-repository-class-yaml.php 

// Need the path to yml files.
$path = 'src/Acme/Bundle/HelloBundle/Resources/config/doctrine/';
// I placed the repositories in there own folder but you do not have to as they can go in the same folder as the Entities.
$repopath = 'Acme\Bundle\HelloBundle\Entity\Repository';
$file_name_stack = glob($path.'*.yml');
$i=0;
foreach($file_name_stack as $key => $file_name)
{
  $content = file_get_contents($file_name);
  $entity_name = substr(basename($file_name), 0, -8);
  $pattern = '/type: entity/i';
  $replacement = 'type: entity'."\r\n".'    repositoryClass: '.$repopath.'\\'.$entity_name.'Repository'."\r";
  $newyaml = preg_replace($pattern, $replacement, $content);
  file_put_contents($file_name,$newyaml);
  $i++;
}
echo $i;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment