File: sharing-objects-between-fixtures.rst

package info (click to toggle)
php-doctrine-data-fixtures 2.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 564 kB
  • sloc: php: 3,148; makefile: 20
file content (77 lines) | stat: -rw-r--r-- 2,338 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Sharing objects between fixtures
================================

Your models are likely to have relationships with each other. Because of
that, it can be interesting to create and persist an object in a
fixture, and then reference it in another fixture.

Assuming you have a ``User`` and a ``Role`` model, here is an example
showing how to use the ``AbstractFixture`` class to do that.

.. note::

   ``AbstractFixture`` implements ``FixtureInterface``, which means the
   requirement mentioned in the :doc:`previous how-to guide
   <loading-fixtures>` is satisfied if you extend ``AbstractFixture``.

.. code-block:: php

    <?php
    namespace MyDataFixtures;

    use Doctrine\Common\DataFixtures\AbstractFixture;
    use Doctrine\Persistence\ObjectManager;

    class UserRoleDataLoader extends AbstractFixture
    {
        public function load(ObjectManager $manager): void
        {
            $adminRole = new Role();
            $adminRole->setName('admin');

            $anonymousRole = new Role();
            $anonymousRole->setName('anonymous');

            $manager->persist($adminRole);
            $manager->persist($anonymousRole);
            $manager->flush();

            // store reference to admin role for User relation to Role
            $this->addReference('admin-role', $adminRole);
        }
    }

And the ``User`` data loading fixture:

.. code-block:: php

    <?php

    namespace MyDataFixtures;

    use Doctrine\Common\DataFixtures\AbstractFixture;
    use Doctrine\Persistence\ObjectManager;

    class UserDataLoader extends AbstractFixture
    {
        public function load(ObjectManager $manager): void
        {
            $user = new User();
            $user->setUsername('jwage');
            $user->setPassword('test');
            $user->setRole(
                $this->getReference('admin-role', Role::class) // load the stored reference
            );

            $manager->persist($user);
            $manager->flush();

            // store reference of admin-user for other Fixtures
            $this->addReference('admin-user', $user);
        }
    }

Note that because that last fixture depends on the first one, the order
in which fixtures are loading becomes important. You can learn more
about how to manage loading order in :doc:`the dedicated guide
<fixture-ordering>`.