Skip to content
This repository was archived by the owner on Sep 23, 2022. It is now read-only.

Doctrine Abstract Fixtures

Gildas Quéméner edited this page Nov 24, 2012 · 2 revisions

A RAD AbstractFixture for Doctrine Data Fixtures

Goal

Provide a basic and easy way to create fixtures using Doctrine Data Fixtures.

Usage

Start by extending the Knp\RadBundle\DataFixtures\AbstractFixture class (this class extends the doctrine AbstractFixture's one, so you have access to all methods as before).

Then, create an ObjectFactory and start adding objects, you can even set default values for your objects!

class LoadMyEntity extends AbstractFixture
{
    public function load(ObjectManager $manager)
    {
        $this
            ->createObjectFactory($manager, 'App\Entity\MyEntity')
            ->setDefaults(['sameAttribute' => 'sameValue'])
            ->add(['name' => 'foo', 'type' => 'bar', 'otherStuff' => 'baz'])
            ->add(['name' => 'goo', 'type' => 'car', 'otherStuff' => 'caz'])
            ->add(['name' => 'goo', 'type' => 'dar', 'otherStuff' => 'daz'])
        ;

        $manager->flush();
    }
}

This will create new objects, persist them and create reference following a simple naming convention.

$this
    ->createObjectFactory($manager, 'App\Entity\MyEntity')
    ->setDefaults(['sameAttribute' => 'sameValue'])
    ->add(['name' => 'foo', 'type' => 'bar', 'otherStuff' => 'baz']) // Reference: MyEntity:foo
    ->add(['name' => 'goo', 'type' => 'car', 'otherStuff' => 'caz']) // Reference: MyEntity:goo
    ->add(['name' => 'goo', 'type' => 'dar', 'otherStuff' => 'daz']) // Reference: MyEntity:goo-1
;

So you can use it later:

$this
    ->createObjectFactory($manager, 'App\Entity\AnotherEntity')
    ->add(['title' => 'Something about foo', 'myEntity' => $this->getReference('MyEntity:foo'))

Reference naming convention

$this
    ->createObject($manager,  'App\Entity\MyEntity')
    ->add(['name' => 'foo',    'type' => 'bar',  'otherStuff' => 'baz']);
;

will generate reference MyEntity:foo (because foo is the value of the first attribute).

if MyEntity:foo is already registered, then it will try to register MyEntity:foo-1 etc...

In case which there is no attribute value, then it will try to create reference MyEntity, MyEntity:1, MyEntity:2, etc...

Clone this wiki locally