Search code examples
symfonydoctrinefixtures

Symfony2 fixtures with order - better way


In DoctrineFixturesBundle if I want execute fixtures in specified order i have to create in any fixture class method like this:

public function getOrder()
{
    return 2;
}

It isn't comfortable way to specify order.

In Laravel Framework I can Do this like this:

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call('PositionsSeeder');
        $this->call('UsersSeeder');
        $this->call('PostsSeeder');
    }
}

My question is: can I do it in this way in symfony?

I see one solution. I can make BaseFixture with this code:

class LoadBrandData extends AbstractFixture
{
    public function load(ObjectManager $manager)
    {
        (new LoadPositionsData())->load(manager);
        (new LoadUsersData())->load(manager);
        (new LoadPostsData())->load(manager);

    }
}

But maybe i can do this better. Can I?


Solution

  • Even if you don't like it, the best way to achieve this is through the getOrder() method.

    Having said that, there are at least two tricks you can use to set the order in other way:

    • Define all the fixtures in one single file. It only makes sense if you don't define a lot of fixtures.
    • Define all the fixtures in one single directory and put the load order as part of the file name (they are loaded alphabetically). This only works if you follow the single-bundle approach to develop Symfony apps.