Load Doctrine Fixtures when using Migrations in Symfony
However, once a project is started, it is often hard to use fixtures because it messes with your data. The trick here is to load only the fixtures you need, only when needed by the migration. This way, a new developer starting with the project could simply run the migrations and have a database ready for testing.
Here is a simple way of loading those fixtures on postUp. You need to pass an array of initialized fixture classes, Doctrine will figure the way to order them by itself.
This is only a proof of concept, it would need some refactoring and testing to be production ready, but you can get the idea.
<?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, | |
)); | |
} | |
} |