igi
igi

Reputation: 125

Symfony 4 / doctrine insert initial database data

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:

Upvotes: 3

Views: 2323

Answers (1)

kalehmann
kalehmann

Reputation: 5011

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()
);

Upvotes: 1

Related Questions