Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 62 ยท Databases with Doctrine

Fixtures and Factories

Fill your Symfony database with test data: DoctrineFixturesBundle classes, references, groups and Foundry factories, plus a runnable seeder stand-in.

An empty database makes a poor development environment. You cannot judge a blog layout without posts, test pagination without a few dozen rows, or notice an N+1 problem with three records. You also do not want to type sample data by hand every time you reset the database. The answer is fixtures: code that creates a known set of data on demand.

Symfony projects usually use two tools for this. DoctrineFixturesBundle gives you classes that load a fixed data set with one command. Foundry gives you factories, small classes that create realistic objects with random-looking but controllable values, which is ideal for tests. This lesson shows both as read-only code, and then builds a runnable seeder stand-in in plain PHP so you can see the mechanics: ordering, references and seeded randomness.

DoctrineFixturesBundle

Install the bundle as a development dependency and generate a class:

Terminal
composer require --dev orm-fixtures
php bin/console make:fixtures

A fixture is a class with one method, load(). You create entities, persist them and flush, exactly as in a controller:

PHP
<?php

namespace App\DataFixtures;

use App\Entity\Category;
use App\Entity\Product;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;

class AppFixtures extends Fixture
{
    public function load(ObjectManager $manager): void
    {
        $books = new Category();
        $books->setName('Books');
        $manager->persist($books);

        foreach (['PHP Handbook' => 2900, 'SQL Cookbook' => 3900] as $name => $price) {
            $product = new Product();
            $product->setName($name);
            $product->setPrice($price);
            $product->setCategory($books);
            $manager->persist($product);
        }

        $manager->flush();
    }
}

Load the data with:

Terminal
php bin/console doctrine:fixtures:load

By default the command purges the database first (it deletes all rows) and asks for confirmation, so it is a development and test tool only. Never run it against production data. Useful options are --append to add rows without purging and --group=demo to run only one group of fixtures. In production deployments the bundle is not even installed, since it is a --dev dependency.

Several fixture classes, references and order

Real projects have many fixture classes: one for categories, one for products, one for users. Products need categories to exist first, and they need a way to point at them. Doctrine fixtures solve both with references and dependencies:

PHP
class CategoryFixtures extends Fixture
{
    public const BOOKS = 'category-books';

    public function load(ObjectManager $manager): void
    {
        $books = new Category();
        $books->setName('Books');
        $manager->persist($books);
        $manager->flush();

        $this->addReference(self::BOOKS, $books);
    }
}

class ProductFixtures extends Fixture implements DependentFixtureInterface
{
    public function load(ObjectManager $manager): void
    {
        $product = new Product();
        $product->setName('PHP Handbook');
        $product->setCategory($this->getReference(CategoryFixtures::BOOKS, Category::class));
        $manager->persist($product);
        $manager->flush();
    }

    public function getDependencies(): array
    {
        return [CategoryFixtures::class];
    }
}

addReference() stores an object under a name, getReference() retrieves it in another class, and getDependencies() tells the loader to run CategoryFixtures first. You can also mark classes with FixtureGroupInterface (a getGroups() method), so that --group=demo loads a bigger data set than --group=test.

This flow is a tiny dependency graph: the loader sorts classes so that each runs after the ones it needs.

flowchart LR
    U["UserFixtures"] --> P["PostFixtures"]
    C["CategoryFixtures"] --> P
    P --> CM["CommentFixtures"]
    U --> CM
    P -.->|"addReference / getReference"| CM

Fixture classes form a dependency graph; the loader runs each one after its dependencies, and references pass objects between them.

The first stand-in builds this idea in plain PHP. Each fixture declares what it depends on, a loader orders them, and a registry holds the references. The database is SQLite in memory, and the data is fixed, so the output is the same every run.

PHP A fixture loader with dependencies and references (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Foundry factories

Hand-written fixtures are good for a small, fixed data set. They get tedious when you need fifty posts with different titles, or when a test needs "a published post by an admin" and nothing else. Foundry is a package built for this. You install it as a development dependency and generate one factory per entity:

Terminal
composer require --dev zenstruck/foundry
php bin/console make:factory

A factory describes the default values of an object. Fields can use the Faker library, so each object looks different:

PHP
<?php

namespace App\Factory;

use App\Entity\Post;
use Zenstruck\Foundry\Persistence\PersistentProxyObjectFactory;

/**
 * @extends PersistentProxyObjectFactory<Post>
 */
final class PostFactory extends PersistentProxyObjectFactory
{
    public static function class(): string
    {
        return Post::class;
    }

    protected function defaults(): array|callable
    {
        return [
            'title' => self::faker()->sentence(4),
            'body' => self::faker()->paragraphs(3, true),
            'published' => self::faker()->boolean(70),
        ];
    }
}

Using it is one line, and you override only what matters:

PHP
PostFactory::createOne();                                 // one random post, saved
PostFactory::createMany(30);                              // thirty random posts
PostFactory::createOne(['title' => 'Hello, Symfony']);    // fixed title, rest random
PostFactory::new(['published' => true])->many(5)->create();

Related objects work too: a factory field can hold another factory, such as 'author' => UserFactory::new(), and Foundry creates the author when it creates the post. In a PHPUnit test class you add the ResetDatabase and Factories traits, and Foundry empties the database between tests, so each test builds exactly the data it needs. That keeps tests short and independent (see Testing with PHPUnit). In a fixtures class you can call the same factories to seed your development database, for example PostFactory::createMany(50) inside AppFixtures::load().

Two habits make factory data trustworthy:

  • Name what matters. If a test checks that unpublished posts are hidden, write PostFactory::createOne(['published' => false]) so the reader sees the cause. Leave everything irrelevant random.
  • Make randomness repeatable. A failing test must fail again on the next run. Faker can be seeded with a fixed number, after which the "random" sequence is always the same; Foundry lets you configure a seed for its Faker instance for this purpose.

Random but repeatable

The second stand-in shows the seeding idea without any package. A factory has defaults, accepts overrides, and draws "random" values from a tiny pseudo-random generator that starts from a seed. The same seed always gives the same data:

PHP A seeded factory (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first two blocks match exactly, which is what a seeded Faker gives you in a real test suite.

Where to use which

Need Tool
A fixed demo data set that every developer loads the same way Fixture classes with doctrine:fixtures:load
Many varied objects for a development database Foundry factories called from a fixture class
Exactly the objects one test needs Foundry factories inside the test
Reference data that production also needs (countries, roles) A migration or a console command, never dev-only fixtures

That last row is a frequent mistake. Fixtures purge the database and exist only on development machines, so data your live application depends on must be created by a migration (see Migrations) or an idempotent command.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does php bin/console doctrine:fixtures:load do by default?

    The default is to delete the existing rows first. Use --append to keep them. Because of this, it is for development and test only.
  2. 2. How does a fixture class make sure categories exist before products are loaded?

    getDependencies() lists the fixture classes that must run first, and the loader orders them accordingly.
  3. 3. What is the main benefit of a Foundry factory over a hand-written fixture in a test?

    Factories keep tests short: you override only the values that matter to the assertion and let the rest be generated.
  4. 4. Why seed the random generator used for test data?

    A seeded generator yields the same sequence every run, which turns random-looking data into repeatable data.
  5. 5. Where should the list of countries your production site needs be created?

    Fixtures purge data and are not installed in production. Data the live app depends on belongs in migrations or commands.

Summary

  • Fixtures create known data on demand; doctrine:fixtures:load purges the database first, so use it only in development and test.
  • Use addReference(), getReference() and getDependencies() to share objects and control the order between fixture classes.
  • Foundry factories define default values (often with Faker), accept overrides and create one or many objects, in fixtures or directly in tests.
  • Seed random data so failures can be reproduced, and name only the values a test cares about.
  • Data that production needs belongs in migrations or commands, not in fixtures.

Next up: Security: Users and Firewalls.