Monday, May 12, 2014

Symfony2 - DataFixtures

Fixtures are used to load a controlled set of data into a database. This data can be used for testing or could be the initial data required for the application to run smoothly (from symfony.com)
So, the DataFixture Bundle is a great way to help initialize your application, e.g. set up an admin user. You can use it all through the development phase continuously, it has an append option. Without the append argument your database will be erased before the fixtures get injected.

If you plan to use this bundle for testing, you can mix it up with the Faker library to create various test data.

When you work on a not so large project it's a good enough bundle to solve your problems. But if the project is a large one and you want to use a more sophisticated way to make fixtures you should use the Alice library! (it has a Bundle for Symfony2 -> AliceBundle)

Alice calls itself an Expressive fixtures generator. It has a lot of handy tools in its toolbox.

You can create fixtures in a config file! Let's see a Static one:
Nelmio\Entity\User:
    user0:
        username: bob
        fullname: Bob
        birthDate: 1980-10-10
        email: bob@example.org
        favoriteNumber: 42
    user1:
        username: alice
        fullname: Alice
        birthDate: 1978-07-12
        email: alice@example.org
        favoriteNumber: 27

Nelmio\Entity\Group:
    group1:
        name: Admins
Take a look at a Fixture Range config:
Nelmio\Entity\User:
    user{1..10}:
        username: bob
        fullname: Bob
        birthDate: 1980-10-10
        email: bob@example.org
        favoriteNumber: 42
The above fixture configuration ends up 10 users, from user1 to user10.

It integrates with the Faker library initially and has a several other helpful features.

No comments:

Post a Comment