Loading fixtures

Let us assume you have an existing project with a User model. To create a fixture for that model, there are three steps:

  1. create a fixture class.
  2. load that fixture with a loader.
  3. execute the fixture with an executor.

Creating a fixture class

Fixture classes have two requirements:

  • They must implement Doctrine\Common\DataFixtures\FixtureInterface.
  • If they have a constructor, that constructor should be invokable without arguments.
1<?php namespace MyDataFixtures; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Persistence\ObjectManager; class UserDataLoader implements FixtureInterface { public function load(ObjectManager $manager): void { $user = new User(); $user->setUsername('jwage'); $user->setPassword('test'); $manager->persist($user); $manager->flush(); } }
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

FixtureInterface is in the Common namespace, because it once was in the doctrine/common package, which was split in several packages. The namespace was retained for backward compatibility.

Loading fixtures

To load a fixture, you can call Loader::addFixture():

1<?php use Doctrine\Common\DataFixtures\Loader; use MyDataFixtures\UserDataLoader; $loader = new Loader(); $loader->addFixture(new UserDataLoader());
2
3
4
5
6
7

It is also possible to load a fixture by providing its path:

1<?php $loader->loadFromFile('/path/to/MyDataFixtures/MyFixture1.php');
2

If you have many fixtures, this can get old pretty fast, and you might want to load a whole directory of fixtures instead of making one call per fixture.

1<?php $loader->loadFromDirectory('/path/to/MyDataFixtures');
2

You can get the added fixtures using the getFixtures() method:

1<?php $fixtures = $loader->getFixtures();
2

Executing fixtures

To load the fixtures in your data store, you need to execute them. This is when you need to pick different classes depending on the type of store you are using. For example, if you are using ORM, you should do the following:

1<?php use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Purger\ORMPurger; $executor = new ORMExecutor($entityManager, new ORMPurger()); $executor->execute($loader->getFixtures());
2
3
4
5
6

Each executor class provided by this package comes with a purger class that will be used to empty your database unless you explicitly disable it.

If you want to append the fixtures instead of purging before loading then pass true to the 2nd argument of execute:

1<?php $executor->execute($loader->getFixtures(), append: true);
2