what are Fixtures symfony ?

After creating the database structure, it would be handy to prepare some test data. We can do this through fixtures. Unfortunately, Symfony2 does not come with any fixtures system, so we need to install it. Type the following:

$ php composer.phar require doctrine/doctrine-fixtures-bundle

Now register the bundle in app/AppKernel.php:

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
        // […]
        if (in_array(/* […] */, array('dev', 'test'))) {
            // …
        $bundles[] = new DoctrineBundleFixturesBundleDoctrineFixturesBundle();
}

If everything goes well, you should see new options when you type the following:

$ php app/console

This should give you a new command called doctrine:fixtures:load.

Now let’s create a simple fixture class to load an example tag.

In the src/AppBundle/DataFixtures/ORM directory, create a file called LoadTagData.php:

<?php

namespace AppBundleDataFixturesORM;

use DoctrineCommonDataFixturesFixtureInterface;
use DoctrineCommonPersistenceObjectManager;
use AppBundleEntityTag;

class LoadUserData implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $tags = ['company', 'home', 'important'];

        foreach ($tags as $tag) {
            $obj = new Tag();
            $obj->setName($tag);
            $manager->persist($obj);
        }

        $manager->flush();
    }
}

Now you should execute this using the following command:

$ php app/console doctrine:fixtures:load

You should see something similar to the following:

Careful, database will be purged. Do you want to continue Y/N ? y
  > purging database
  > loading AppBundleDataFixturesORMLoadUserData

This loads the fixtures data to our database. It is possible to create more sophisticated fixtures, use a container, change the load order,

Deven Rathore

Deven is an Entrepreneur, and Full-stack developer, Constantly learning and experiencing new things. He currently runs CodeSource.io and Dunebook.com.

Published by
Deven Rathore

Recent Posts

Choose An App Development Company In 4 Easy Ways

The mobile app industry has been popular in recent years. Thanks to the continuing technological…

2 hours ago

3 Ways to Get the Most Out of Your University’s Virtual Computer Lab

IT is more important than ever in the world of higher education, and yet with…

3 hours ago

Top Tips for Learning Java Programming

If you’re here for the top tips, we assume you’re ahead of the “how to…

3 days ago

Neural Networks for Creating Blog Texts

The world is progressing at unprecedented rates at the current moment, especially in terms of…

4 days ago

Top 20 Opensource Python Tkinter Projects

This article will highlight the Top 20 Opensource Python Tkinter Projects which we believe will…

6 days ago

Beginners guide to Sneaker Proxies

With their numerous applications in streamlining the data flow, securing both the servers and the…

1 week ago