3
votes

I am using symfony 4.2 and looking for a way to insert initial data to the database. What I was trying to create is something like an initial setup script that do some sql inserts (like fixtures but for the production environment as well) that can be called by a console command.

I was thinking of using the postUp function in the doctrine migration class but I don’t want to rewrite this function for every production environment I set up. Is there a way to use doctrines migration functionality for this purpose or is there a preferred way?

Example workflow:

  • Install symfony by cloning the git repository
  • Execute migrations to create / update the database tables
  • Execute the setup script to insert the needed default values into the database tables
1
So, create a command and run it.u_mulder
At the end, I did it that way. I created a custom command to load the doctrine manager by an ContainerInterface. I wasn’t familiar with the creation of a custom command. Here is the reference I used: symfony.com/doc/current/console.htmligi

1 Answers

1
votes

Using the doctrine fixtures bundle in production

While this is discouraged because you can accidentally drop your production database with this, I do see some valid use cases for using the dotrine fixtures bundle in a production environment.

You can edit your config/bundles.php to enable the doctrine fixtures bundle in the production environment.

Change

Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],

to

Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['all' => true],

Create your own command for fixture loading

Using doctrine functionality to manually load the fixtures is also discouraged, but that way you can add additional checks, for example only populate a fresh database.

$fixtures = (new \Doctrine\Common\DataFixtures\Loader())->loadFromDirectory(__DIR__ . '/../src/DataFixture');
$loader = new \Doctrine\Bundle\FixturesBundle\Loader\SymfonyFixturesLoader(new \Symfony\Component\DependencyInjection\Container());
$loader->addFixtures(
    array_map(
        function ($fixture) {
            return [
              'fixture' => $fixture,
              'groups' => []
            ];
        },
        $fixtures
    )
);

$purger = new Doctrine\Common\DataFixtures\Purger\ORMPurger($entityManager);

$executor = new Doctrine\Common\DataFixtures\Executor\ORMExecutor($entityManager, $purger);
$executor->execute(
    $loader->getFixtures()
);