Hi Symfonians ! :)

I am actually spending a lot of time on testing Symfony2. When building an application, one of the first thing you will have to do is to insert initial data, also called fixtures, so you can use and test your application. There is a documentation on the Symfony website about this subject, it uses the DoctrineFixturesBundle.

It works very well, but I wanted to use YAML files "a la symfony1". So I ended up with this simple solution:

The base Loader class:

First, I create a base Loader class that others entities loaders will extend:

The getModelFixtures() function will load the YAML file corresponding to the current entity, the getModelFile() function will have to be implemented by sub-loaders. The class implements the ContainerAwareInterface so we can access the DIC in the loaders.

The Category loader:

The YAML file:

Both jobs and categories YAML files are almost equal to the Jobeet1 tutorial ones.

The loader class:

The getModelFixtures() function retrieves the fixtures for the Category entity and then you just have to iterate over the array. At each iteration we add a reference to the entity so it can be used in other loaders. (as a foreign key)

The Job loader:

The YAML file:

The loader class:

Same here, but:

  • For each iteration we retrieve the proper category reference we already built in the Category loader (line 30).
  • In Jobeet1 there was a loop directly in the YAML file in order to add lot of job rows, now we can do this loop in our loader: duplicateLastJob().
  • There is also a special case where we force a value for the expiresAt date field that would be overridden by the Job object life-cycle callbacks otherwise.

I think this a good approach as you have the ease of writing YAML without loosing the possibility to handle complex or edge cases with PHP. You can find the code on github.

See you ! COil :)

PS: This tutorial was tested with Symfony Standard Edition 2.0.9.
PS2: If you have a blog post about fixtures, let me know so I can add it below.

Other posts about fixtures: