what are Fixtures symfony ?

http://symfony.com/logos/symfony_black_01.png?v=4

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,

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares