Creating symfony fixtures are a great way to setup your development or testing environments in your project. In some situations we need to have some demo data in our database in order to test our applications properly. This is the moment when fixtures should be used. Fixtures used to load data to database programatically. And once setted up, they can be easily reused everytime you need them.

Fixtures in Symfony are provided by default and they are a part of Doctrine library, bundled in DoctrineFixturesBundle. If somewhy you don’t have this bundle already, you can simply install it with composer, running this command:

composer require --dev doctrine/doctrine-fixtures-bundle

Creating Symfony Fixtures Class

Let’s say our application needs some demo data for Book and Shelf entities, which would have relationship one-to-many from Shelf entity and many-to-one from Book entity. So let’s create our entities:

So that we have our entities for testing, let’s create fixtures:

Fixtures should lie in *Bundle/DataFixtures/ORM catalog, this is a default path in symfony. Now that we setted up fixtures, to load them we need run a console command:

php app/console doctrine:fixtures:load

Creating symfony fixtures

If no red lines appear, then congratulations! You have loaded fixtures and now the data can be seen in database.

Setting Relationships And Fixture Order

We have setted up simple fixture. But often you will find that just creating and persisting new entities will be not enough. For example, we need to set up relationships between entities in different fixture classes. Let’s update our fixtures to use relationship and properly order loading of fixtures:

Here we implemented OrderFixtureInterface in class declarations. This tell us, that we need to implement getOrder() function which returns order number when fixture should load. To set Book relation for Shelf, we need first load shelf data, and set reference, as you can see in above example. When loading book data, we can get the reference to that shelf, and set it to books. Let’s run command one more time, which will remove previous data in database and load new data, with relations properly setted.