Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 452
Kamil P Avatar asked Nov 29 '25 00:11

Kamil P


2 Answers

You can use Doctrine DependentFixtureInterface; please check below example:

namespace MyDataFixtures;

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

class MyFixture extends AbstractFixture implements DependentFixtureInterface
{
    public function load(ObjectManager $manager)
    {}

    public function getDependencies()
    {
        return array('MyDataFixtures\MyOtherFixture'); // fixture classes fixture is dependent on
    }
}

class MyOtherFixture extends AbstractFixture
{
    public function load(ObjectManager $manager)
    {}
}

Source: https://github.com/doctrine/data-fixtures

like image 168
Geo Salameh Avatar answered Dec 01 '25 10:12

Geo Salameh


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.
like image 23
Javier Eguiluz Avatar answered Dec 01 '25 08:12

Javier Eguiluz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!