Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

QuestionTag Fixtures & DateTimeImmutable with Faker

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

We no longer have a ManyToMany relationship between Question and Tag. Instead, each Question has many QuestionTag objects and each QuestionTag object is related to one Tag. This means that setting and using this relation - the relationship between Question and Tag - just changed. Let's update the fixtures to reflect this.

Generating & Configuring the QuestionTag Factory

First, since we now have a QuestionTag entity, we are going to be creating and persisting QuestionTag objects directly. So let's generate a Foundry factory for it. At your terminal, run:

symfony console make:factory

And choose QuestionTag. Go open that up: src/Factory/QuestionTagFactory.php.

... lines 1 - 2
namespace App\Factory;
use App\Entity\QuestionTag;
use App\Repository\QuestionTagRepository;
use Zenstruck\Foundry\RepositoryProxy;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
... lines 11 - 28
final class QuestionTagFactory extends ModelFactory
{
public function __construct()
{
parent::__construct();
// TODO inject services if required (https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services)
}
protected function getDefaults(): array
{
return [
// TODO add your default values here (https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories)
'taggedAt' => self::faker()->datetime(),
];
}
protected function initialize(): self
{
// see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization
return $this
// ->afterInstantiate(function(QuestionTag $questionTag) {})
;
}
protected static function getClass(): string
{
return QuestionTag::class;
}
}

In getDefaults(), our job, as usual, is to add all the required fields. Set question to QuestionFactory::new() and do the same thing for tag, setting that to TagFactory::new().

... lines 1 - 28
final class QuestionTagFactory extends ModelFactory
{
... lines 31 - 37
protected function getDefaults(): array
{
return [
'question' => QuestionFactory::new(),
'tag' => TagFactory::new(),
'taggedAt' => self::faker()->datetime(),
];
}
... lines 46 - 58
}

As a reminder, the new() method returns a QuestionFactory instance. So we're assigning the question attribute to a QuestionFactory object. We talked earlier about how this is better than calling createOne() because, when you set a relationship property to a factory instance, Foundry will use that to create the Question object... but only if it needs to.

Anyways with this setup, when we use this factory, it will create a brand new Question and a brand new Tag each time it makes a QuestionTag.

We can see this. Open up the fixtures class and say QuestionTagFactory::createMany(10). I'm going to put a return statement here because some of the code below is currently broken.

... lines 1 - 9
use App\Factory\QuestionTagFactory;
... lines 11 - 14
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
TagFactory::createMany(100);
QuestionTagFactory::createMany(10);
return;
... lines 24 - 48
}
}

Let's try this:

symfony console doctrine:fixtures:load

Handling DateTimeImmutable & Faker

And... it fails! But... for an unrelated reason. It says:

QuestionTag::setTaggedAt() argument 1 must be a DateTimeImmutable instance, DateTime given.

This is subtle... and related to Faker. In Faker, when you say self::faker()->datetime(), that returns a DateTime object. No surprise!

But if you look at the QuestionTag entity, the taggedAt field is set to a datetime_immutable Doctrine type. This means that, instead of that property being a DateTime object, it will be a DateTimeImmutable object. Really... the same thing... except that DateTimeImmutable objects can't be changed.

The point is, the type-hint on the setter is DateTimeImmutable... but we're trying to pass a DateTime instance... which isn't the same. The easiest way to fix this is to update the fixtures. Wrap the value with DateTimeImmutable::createFromMutable()... which is a method that exists just for this situation.

... lines 1 - 28
final class QuestionTagFactory extends ModelFactory
{
... lines 31 - 37
protected function getDefaults(): array
{
return [
... lines 41 - 42
'taggedAt' => \DateTimeImmutable::createFromMutable(self::faker()->datetime()),
];
}
... lines 46 - 58
}

And if we reload the fixtures now...

symfony console doctrine:fixtures:load

No errors! Run:

symfony console doctrine:query:sql 'SELECT * FROM question_tag'

And... cool! We have 10 rows. Now query the question table:

symfony console doctrine:query:sql 'SELECT * FROM question'

And this also has 10 rows. That proves that, each time the factory creates a QuestionTag, it creates a brand new Question to relate to it.

So... this works... but it's not really what we want. Instead of creating new questions, we want to relate each QuestionTag to one of the published questions that we're creating in our fixtures.

Let's do that next, by doing some seriously cool stuff with Foundry.

Leave a comment!

0
Login or Register to join the conversation
Cat in space

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

This tutorial also works great for Symfony 6!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=8.1",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "babdev/pagerfanta-bundle": "^3.3", // v3.3.0
        "composer/package-versions-deprecated": "^1.11", // 1.11.99.3
        "doctrine/doctrine-bundle": "^2.1", // 2.4.2
        "doctrine/doctrine-migrations-bundle": "^3.0", // 3.1.1
        "doctrine/orm": "^2.7", // 2.9.5
        "knplabs/knp-markdown-bundle": "^1.8", // 1.9.0
        "knplabs/knp-time-bundle": "^1.11", // v1.16.1
        "pagerfanta/doctrine-orm-adapter": "^3.3", // v3.3.0
        "pagerfanta/twig": "^3.3", // v3.3.0
        "sensio/framework-extra-bundle": "^6.0", // v6.2.1
        "stof/doctrine-extensions-bundle": "^1.4", // v1.6.0
        "symfony/asset": "5.3.*", // v5.3.4
        "symfony/console": "5.3.*", // v5.3.7
        "symfony/dotenv": "5.3.*", // v5.3.7
        "symfony/flex": "^1.3.1", // v1.17.5
        "symfony/framework-bundle": "5.3.*", // v5.3.7
        "symfony/monolog-bundle": "^3.0", // v3.7.0
        "symfony/runtime": "5.3.*", // v5.3.4
        "symfony/stopwatch": "5.3.*", // v5.3.4
        "symfony/twig-bundle": "5.3.*", // v5.3.4
        "symfony/validator": "5.3.*", // v5.3.14
        "symfony/webpack-encore-bundle": "^1.7", // v1.12.0
        "symfony/yaml": "5.3.*", // v5.3.6
        "twig/extra-bundle": "^2.12|^3.0", // v3.3.1
        "twig/string-extra": "^3.3", // v3.3.1
        "twig/twig": "^2.12|^3.0" // v3.3.2
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.3", // 3.4.0
        "symfony/debug-bundle": "5.3.*", // v5.3.4
        "symfony/maker-bundle": "^1.15", // v1.33.0
        "symfony/var-dumper": "5.3.*", // v5.3.7
        "symfony/web-profiler-bundle": "5.3.*", // v5.3.5
        "zenstruck/foundry": "^1.1" // v1.13.1
    }
}
userVoice