DEV Community

Hanane Kacemi
Hanane Kacemi

Posted on

Symfony & Doctrine: Part 4

While developing a new app, we usually don’t have any data on DB, it’s common to add fake data to do our tests, either manually or using libraries. With Symfony we have a bundle called “Doctrine Fixture”, I tried it and below are my notes about it.

To install it, use: composer require orm-fixtures --dev
New folder “DataFixtures” is created under “src”, it will contain PHP Classes where we create objects to persist into DB.

I like to keep things organized so I will create many fixtures classes instead of adding all dummy data to AppFixtures generated by default.

In order to reuse objects across fixtures Classes we use object References(line 32 to 34) and we can get easily the reference in the 2nd Fixture Class (line 15)

Category Fixtures
Job Fixtures

When using multiple fixtures, we need to specify the order in which fixtures will be loaded otherwise Doctrine will use the alphabetical order, which may result in errors if objects referenced are not yet created. To do so, we need to implement DependentFixtureInterface and then add getDependencies() to specify fixtures to load before.
Fixtures dependencies

To add data to db, we run : symfony console doctrine:fixtures:load

I have also tried an other bundle that helps to generate dummy data instead of setting values manually (if you lack inspiration like me :D ) to add it : composer require fzaninotto/faker --dev

Once installed, we can use methods availables in this library to get a name, address, country, slug, numbers... It's awesome.

Below my JobFixtures class after using this library
JobFixtures using Faker

more infos on the documentation : https://github.com/fzaninotto/Faker

Thanks for reading :)

Discussion (0)