Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Fixtures: Dummy Data Rocks

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

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:

... 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:

... 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:

... 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!

33
Login or Register to join the conversation
Default user avatar
Default user avatar Lluís Puig Ferrer | posted 4 years ago

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!

1 Reply

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!

1 Reply
Default user avatar
Default user avatar Michael | posted 4 years ago

Hello there,

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

Reply
Default user avatar

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

Reply

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

Reply
Default user avatar

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...

Reply

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!

Reply
Dino2014 D. Avatar
Dino2014 D. Avatar Dino2014 D. | posted 4 years ago

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.

Reply

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!

Reply
Dino2014 D. Avatar

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?

Reply

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

Reply
Dino2014 D. Avatar

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?

Reply

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!

Reply
Dino2014 D. Avatar

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

1 Reply
Default user avatar

And what about using DoctrineFixturesBundle with 'rich entities' ? (which means no 'setter' inside the entity)

Reply

Hey Xavier!

Ah, great question :). Actually, tomorrow and the next day, we'll release 2 chapters that talk about Fixtures in Symfony 4. I've changed my approach slightly, in part because Alice has become a pain to work with. Here is the link to those chapters - you can read the content now, the videos will be there over the next 2 days:

* https://knpuniversity.com/s...
* https://knpuniversity.com/s...

The main point is that, if you don't use Alice, then it is, once again, your responsibility to call whatever methods you want to set data on your entity. This means you can use any methods you want to set the data on it :).

Cheers!

Reply
Default user avatar
Default user avatar Kaira S | posted 4 years ago

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

Reply

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!

1 Reply
Default user avatar

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!

47 Reply

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

Reply
Patrick Avatar
Patrick Avatar Patrick | posted 4 years ago

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.

Reply

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!

Reply
Dmitry V. Avatar

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.

Reply

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!

Reply
Dmitry V. Avatar

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!

Reply

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

Reply

BTW, are you on Symfony 4?

Reply
Default user avatar
Default user avatar Sebastian Majchrzak | posted 4 years ago

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.

Reply
Victor N. Avatar

Regarding same error ("Could not find any fixture services to load") when you use Symfony 3.4: to solve it, you just need to have the fixtures class extend the Doctrine\Bundle\FixturesBundle\Fixture class instead of implementing FixtureInterface as described in this chapter's video - for more details, please check https://symfony.com/doc/cur..., like below:

namespace AppBundle\DataFixtures\ORM;

...
use Doctrine\Bundle\FixturesBundle\Fixture;
...

class LoadFixtures extends Fixture
{
// ... etc
}

Reply

Good tip! We use an interface that's implemented by that Fixture class to know that this is a fixture :)

Reply

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!

Reply
Richard Avatar
Richard Avatar Richard | posted 4 years ago

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

-1 Reply

Haha, cheers! :D

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=5.5.9",
        "symfony/symfony": "3.1.*", // v3.1.4
        "doctrine/orm": "^2.5", // v2.7.2
        "doctrine/doctrine-bundle": "^1.6", // 1.6.4
        "doctrine/doctrine-cache-bundle": "^1.2", // 1.3.0
        "symfony/swiftmailer-bundle": "^2.3", // v2.3.11
        "symfony/monolog-bundle": "^2.8", // 2.11.1
        "symfony/polyfill-apcu": "^1.0", // v1.2.0
        "sensio/distribution-bundle": "^5.0", // v5.0.22
        "sensio/framework-extra-bundle": "^3.0.2", // v3.0.16
        "incenteev/composer-parameter-handler": "^2.0", // v2.1.2
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "knplabs/knp-markdown-bundle": "^1.4", // 1.4.2
        "doctrine/doctrine-migrations-bundle": "^1.1" // 1.1.1
    },
    "require-dev": {
        "sensio/generator-bundle": "^3.0", // v3.0.7
        "symfony/phpunit-bridge": "^3.0", // v3.1.3
        "nelmio/alice": "^2.1", // 2.1.4
        "doctrine/doctrine-fixtures-bundle": "^2.3" // 2.3.0
    }
}