Buy

Fixtures: Dummy Data Rocks

It's so much more fun to develop when your database has real, interesting data. We do have a way to add some fake genuses into the database, but they're not very interesting. And when we need more dummy data - like users and genus notes - it's just not going to work well.

Nope - we can do better. I'm dreaming of a system where we can quickly re-populate our local database with a really rich set of fake data, or fixtures.

Search for DoctrineFixturesBundle. This bundle is step 1 towards my dream. Copy the composer require line and paste that into the terminal. But hold on! I also want to download something else: nelmio/alice. That's just a normal PHP library, not a bundle. And it's going to make our fixtures amazing:

composer require --dev doctrine/doctrine-fixtures-bundle nelmio/alice:2.1.4

Tip

Be sure to install version 2 of Alice, as version 3 has many changes: $ composer require --dev nelmio/alice:2.1.4

Conditionally Load Dev Libraries

Oh, and the --dev flag isn't too important. It means that these lines will be added to the require-dev section of composer.json:

68 lines composer.json
{
... lines 2 - 31
"require-dev": {
... lines 33 - 34
"nelmio/alice": "^2.1",
"doctrine/doctrine-fixtures-bundle": "^2.3"
},
... lines 38 - 66
}

And that's meant for libraries that are only needed for development or to run tests.

When you deploy - if you care enough - you can tell composer to not download the libraries in this section. But frankly, I don't bother.

While Composer is communicating with the mothership, copy the new bundle line and add it to AppKernel. But put it in the section that's inside of the dev if statement:

57 lines app/AppKernel.php
... lines 1 - 5
class AppKernel extends Kernel
{
public function registerBundles()
{
... lines 10 - 25
if (in_array($this->getEnvironment(), array('dev', 'test'), true)) {
... lines 27 - 30
$bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
}
... lines 33 - 34
}
... lines 36 - 55
}

This makes the bundle - and any services, commands, etc that it gives us - not available in the prod environment. That's fine for us - this is a development tool - and it keeps the prod environment a little smaller.

Creating the Fixture Class

Anyways, this bundle gives us a new console command - doctrine:fixtures:load. When we run that, it'll look for "fixture classes" and run them. And in those classes, we'll create dummy data.

Copy the example fixture class. In AppBundle, add a DataFixtures/ORM directory. Then, add a new PHP class called - well, it doesn't matter - how about LoadFixtures. Paste the example class we so aggressively stole from the docs and update its class name to be LoadFixtures:

21 lines src/AppBundle/DataFixtures/ORM/LoadFixtures.php
... lines 1 - 2
namespace AppBundle\DataFixtures\ORM;
... lines 4 - 5
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
class LoadFixtures implements FixtureInterface
{
public function load(ObjectManager $manager)
{
... lines 13 - 19
}
}

Clear out that User code. We need to create Genuses.. and we have some perfectly good code in newAction() we can steal to do that. Paste that it:

21 lines src/AppBundle/DataFixtures/ORM/LoadFixtures.php
... lines 1 - 4
use AppBundle\Entity\Genus;
... lines 6 - 8
class LoadFixtures implements FixtureInterface
{
public function load(ObjectManager $manager)
{
$genus = new Genus();
$genus->setName('Octopus'.rand(1, 100));
$genus->setSubFamily('Octopodinae');
$genus->setSpeciesCount(rand(100, 99999));
$manager->persist($genus);
$manager->flush();
}
}

The $manager argument passed to this function is the entity manager. Use it to persist $genus and don't forget the Genus use statement. Oh, and only one namespace - whoops!

I know this is not very interesting yet - stay with me. To run this, head over to the terminal and run:

./bin/console doctrine:fixtures:load

This clears out the database and runs all of our fixture classes - we only have 1. Now, head back to the list page. Here is our one random genus. So it's kind of cool... but I know - totally underwhelming. Enter Alice: she makes fixtures fun again.

Leave a comment!

  • 2018-01-16 Diego Aguiar

    Have you tried PhpStorm? We have a free tutorial about it: https://knpuniversity.com/s...

  • 2018-01-16 Kaira S

    Thanx,

    Here's a little trick I figured out, I have used notepad++ for a long time and a few days ago it hit me. Why am I manually chasing down typos?

    So I opened up notepad++ with other view pane open, and pasted my code in the left view and code from the script here into the right view, then used notepad++ comparison plugin to compare the both against each other.

    It works great....Example: I wrote out a public function and ended it with a colon ":" instead of semi-colon ";" I over looked it three times before comparing against the script using notepad++.

    I've used Linters in Atom before and this is relatively quicker, easier and free... I like free :)

    Happy Coding Everyone!

  • 2018-01-16 Diego Aguiar

    Hey Kaira S

    I'm sorry to hear that you had to spent so many hours figuring out how to fix a pesky problem, the good part is that you now have a new trick into your trick's belt.
    Oh, and thanks for sharing your solution :)

    Cheers!

  • 2018-01-15 Kaira S

    Had trouble loading doctrine-fixtures-bundle and nelmio/alice... when trying to do the require --dev for them I got all kinds of errors about
    symfony/symfony 3.1.4 satisfiable by v3.1.4 and so forth....on a bunch of bundles.

    Luckily, I have been saving my files from the project at the end of each chapter to a start directory in a directory for the next chapter.

    I dumped my current files and reloaded chapter 8 files without the .idea folder and copied the composer.json and composer.lock files from the finish folder of this course.

    Then it was just a matter of running composer install in my terminal and boom....everything works and all I had to do is proceed with the rest of this chapter, after the require of fixtures and alice.

    So far so good...not at all sure why I had incompatibility issues and really don't care after having similar issue earlier and spending 4 hours researching just to find out I needed double quotes instead of single quotes for windows to agree to work with symfony....Just part of the journey I guess..lol

    Anyway,
    Hope this helps others that might be having trouble.

    Have A Great Day Everyone

  • 2017-12-07 Diego Aguiar

    Hey Sebastian Majchrzak

    You are correct, don't exclude your fixtures directory in services.yaml.
    If you want to learn more about the changes of the container, you can watch our "Symfony 3.3" tutorial (The container didn't change too much from 3.3 to 4)
    https://knpuniversity.com/s...

    Cheers!

  • 2017-12-07 Diego Aguiar

    BTW, are you on Symfony 4?

  • 2017-12-07 Diego Aguiar

    Ohh, so things have changed in 3.0 version. Thanks for sharing your findings!

  • 2017-12-07 Sebastian Majchrzak

    If you use symfony4 with fixtures and bin/console doctrine:fixtures:load has an error like this "Could not find any fixture services to load." this could be a reason
    "
    App\:
    resource: '../src/*'
    # you can exclude directories or files
    # but if a service is unused, it's removed anyway
    exclude: '../src/{DataFixtures,Entity,Migrations,Tests}'
    "
    Remove temporally from the excluded path in service.yml the DataFixtures. It should be like this

    "
    App\:
    resource: '../src/*'
    # you can exclude directories or files
    # but if a service is unused, it's removed anyway
    exclude: '../src/{Entity,Migrations,Tests}'
    "

    I hope it can help.

  • 2017-12-07 Dmitry Vishin

    Hi! I use 3.0 and need to say that if my class IMPLEMENTS "FixtureInterface" I have to specify DataFixtures folder in config/services.yaml and without this config if it is EXTENDS "Fixture". Thanx a lot!

  • 2017-12-06 Diego Aguiar

    Hey Dmitry Vishin

    Can you tell me which version of "doctrine/doctrine-fixtures-bundle" library are you using?
    I tried in 2.3 and it worked, but maybe they changed it for the latest version

    Also, you can run

    php bin/console doctrine:fixtures:load --help

    to check out all available options (Maybe they changed the option name?)

    Cheers!

  • 2017-12-06 Dmitry Vishin

    Hi Diego! The "--fixtures" option does not exist anymore. Even 4.0.1 I have to implement service configuration to show Symfony my DataFixtures folder in config/services.yaml

    services:
    ...
    App\DataFixtures\:
    resource: '../src/DataFixtures'
    tags: [doctrine.fixture.orm]

    After that I can place any DataFixture class inside src/DataFixtures folder and it works fine. Think about this information as a note for your tutorial.

  • 2017-03-21 Diego Aguiar

    Hey Dan!
    Indeed, that's the default path for fixtures, you don't have to follow that structure if you don't like it, but you will have to specify the new path in the command, like this:

    bin/console doctrine:fixtures:load --fixtures=/path/to/fixture

    Ah and thanks for mention it, we should add a note in the video :)

    Have a nice day!

  • 2017-03-21 Dan Abrey

    When you run doctrine:fixtures:load, the default path that fixture-loading classes are looked for is AppBundle/DataFixtures/ORM - that's how it knows to load the LoadFixtures class and run the load method.

    This was the first time during this course that I thought "wait, how did that happen?" without explanation, which is joyfully rare! But still I thought worth mentioning.

  • 2017-02-22 weaverryan

    Haha, cheers! :D

  • 2017-02-20 maxii123

    Enter Alice? I quick double take there. Excellent series.

  • 2016-03-17 weaverryan

    You got it :). The video for this chapter will be posted soon.

  • 2016-03-17 Michael

    Actually, it must be from here: http://symfony.com/doc/curr...

  • 2016-03-17 Michael

    Hello there,

    "Copy the example fixture class". Where do we find this?