Buy
This tutorial has a new version, check it out!

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:

Tip

If you are on Symfony 3.2 or higher, you don't have to specify the DoctrineFixturesBundle version constraint

composer require --dev doctrine/doctrine-fixtures-bundle:2.3.0 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-03-12 Diego Aguiar

    Symfony docs has a menu for choosing which version of Symfony docs you want to read, but, thanks for the link, I didn't know about that page, it looks awesome!

    Cheers!

  • 2018-03-11 Ben

    Given that the documentation has changed a lot. Here's the web archive version of the docs used in the video:
    https://web.archive.org/web...

  • 2018-02-15 Victor Bocharsky

    Hey LIuis,

    Thanks for sharing it with others! Yes, we use DoctrineFixturesBundle version "^2.3" in this screencast, but 3.x already available which has some BC breaks because it's a major version change. So to match this course, use "^2.3" version constraint which btw even supports Symfony 4. Unfortunately, DoctrineFixturesBundle does not have changelog, so if someone want to use the new 3.x version - they need to manually check BC breaks on GitHub comparing 2.x and 3.x branches or look over their updated docs.

    Cheers!

  • 2018-02-14 LluĂ­s Puig Ferrer

    When trying to install doctrine-fixtures-bundle I get an error. I'm with Symfony version 3.1.10 and I need to install it adding "^2.0.0" like this:
    composer require --dev "doctrine/doctrine-fixtures-bundle:^2.0.0"

    Hope that helps someone!

    Cheers!

  • 2018-01-29 walter pothof

    Removing composer and reinstalling did it.
    I was able to install a new bundle again.
    Thanks!

  • 2018-01-29 Diego Aguiar

    You are on windows right? I just found a quick video that shows how to do it (it looks simple) https://www.youtube.com/wat...

    > Does that remove and add affect my website or will composer just be temporarely not available and be available again when reinstalled?

    Exactly that, you won't be able to use composer temporarely (until you re-install it), but, your site should be running ok (just don't try to update any dependency through composer)

    > What will happen with the repo and files folder inside the composer folder if i remove the composer?

    Hmm, I don't know for certain, I believe they will be removed but you should not worry about it, once you re-install it, you should be able to run "$ composer install" at your projects root

    Cheers!

  • 2018-01-29 walter pothof

    Its my computer indeed. How do i remove composer globaley and how would i reinstall it again globaly?
    Does that remove and add affect my website or will composer just be temporarely not available and be available again when reinstalled?
    What will happen with the repo and files folder inside the composer folder if i remove the composer?

  • 2018-01-29 Diego Aguiar

    Hmm, interesting... Do you own that computer? did you install composer globally?
    If you have nothing to lose, you may want to re-install composer globally

  • 2018-01-29 walter pothof

    I have run the command both normal and as administrator. Both give the same error:
    hash_file(C:/Users/Walter/AppData/Local/Composer/repo/https---packagist.org/provi...
    failed to open stream: Permission denied

    Inside the repo folder i see this as permissions if i use the windows powershell:
    Mode LastWriteTime Length Name
    ---- ------------- ------ ----
    d----- 15-12-2017 15:03 https---packages.drupal.org-8
    d----- 28-1-2018 18:16 https---packagist.org

    Every file inside the https--packagist.org folder has the folowing permissions:
    Mode LastWriteTime Length Name
    ---- ------------- ------ ----
    -a---- 28-1-2018 12:57 731236 p-provider-2013.json

    I am not able to chmod 777 filename in that folder (tried to set permission tto 777)

    What could i do?

  • 2018-01-29 Diego Aguiar

    Hey walter pothof

    Look's like you are missing some permissions to write inside Composer folder, try running that command again as administrator (this is not recommended but just to be sure that the problem really is about permissions), if it works, then for some reason you lost your writting permission on that folder; you would only have to tweak the permissions of that folder and everything should be fine

    Cheers!

  • 2018-01-28 walter pothof

    Hi, when i try to install the doctrine-fixture-bundle i get an error about permission denied:
    hash_file(C:/Users/xxx/AppData/Local/Composer/repo/https---packagist.org/provi... fa
    iled to open stream: Permission denied

    In fact whateven bundle i try to install i get this error.
    Anyone got an idea how i can solve this. I must have done something during this course i should not have cause i was able to install the doctrine cache bundle in an other cource from here.
    But now ... nothing can be installed no more using composer. (composer update does work tho)
    I realy apriciate help.

  • 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?