Data Fixture & Demo Data

Hope you enjoy with generating/creating entity. It’s awesome you done it. Now we are going to look around. How to load data fixtures on the created entities.

For this, we are using the FixtureInterface to implement the method and load the data into the database.

Let’s create a PHP class in our bundle location <Bundle Name>/Migrations/Data/ORM,

let’s name as LoadTasks.php

<?php

namespace BlogBundle\Migrations\Data\ORM;

use BlogBundle\Entity\Priority;
use BlogBundle\Entity\Task;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

class LoadTasks implements FixtureInterface
{

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $majorPriority = new Priority();
        $majorPriority->setLabel('major');
        $manager->persist($majorPriority);

        $importantTask = new Task();
        $importantTask->setSubject('Important task');
        $importantTask->setDescription('This is important task');
        $importantTask->setDueDate(new \DateTime('+1 week'));
        $importantTask->setPriority($majorPriority);
        $manager->persist($importantTask);

        $minorPriority = new Priority();
        $minorPriority->setLabel('minor');
        $manager->persist($minorPriority);

        $unimportantTask = new Task();
        $unimportantTask->setSubject('Unimportant Task');
        $unimportantTask->setDescription('This is unimportant task');
        $unimportantTask->setDueDate(new \DateTime('+2 weeks'));
        $unimportantTask->setPriority($minorPriority);
        $manager->persist($unimportantTask);

        $manager->flush();
    }
}

Then you can able to migrate the command using

Selection_053.png

That’s it. Now check your database. The data we load is inside the database.

Selection_054.png

Yeah! We made the data fixture.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s