Skip to content

Instantly share code, notes, and snippets.

@lavoiesl
Last active October 18, 2023 19:23
Show Gist options
  • Save lavoiesl/77375da08b3274aa6440 to your computer and use it in GitHub Desktop.
Save lavoiesl/77375da08b3274aa6440 to your computer and use it in GitHub Desktop.
Load Doctrine Fixtures when using Migrations in Symfony: AbstractFixtureMigration
<?php
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader as Loader;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class AbstractFixtureMigration extends AbstractMigration implements ContainerAwareInterface
{
use FixtureMigrationTrait;
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function loadFixtures(array $fixtures, $append = true)
{
$em = $this->container->get('doctrine.orm.entity_manager');
$loader = new Loader($this->container);
array_map(array($loader, 'addFixture'), $fixtures);
$purger = null;
if ($append === false) {
$purger = new ORMPurger($em);
$purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE);
}
$executor = new ORMExecutor($em, $purger);
$output = new ConsoleOutput;
$executor->setLogger(function($message) use ($output) {
$output->writeln(sprintf(' <comment>></comment> <info>%s</info>', $message));
});
$executor->execute($loader->getFixtures(), $append);
}
}
<?php
use Doctrine\DBAL\Schema\Schema;
use AcmeBundle\DataFixtures\ORM as Fixtures;
class Version1 extends AbstractFixtureMigration
{
public function up(Schema $schema)
{
// ...
}
public function down(Schema $schema)
{
// ...
}
public function postUp(Schema $schema)
{
$this->loadFixtures(array(
new Fixtures\LoadMyData,
new Fixtures\LoadMyOtherData,
));
}
}
@VincentClair
Copy link

Thanks, very helpful

@dextervip
Copy link

Great! It is missing FixtureMigrationTrait however it is unused anyway, just removed it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment