Symfony 3 的 Doctrine Fixtures 的多个文件

Multiple files for Doctrine Fixtures for Symfony 3

我正在使用包 Doctrine:Fixtures 加载 bbdd throw 实体的示例,因为我在项目中独自工作,所以没问题。

但是现在,我的项目中有一位同事,我们想知道是否可以为加载设置不同的文件。

我在 git 中有自己的灯具文件,我不想让他修改这个文件。我想要一个专为他准备的特殊文件,允许他在需要这个灯具文件时随时进行修改。所以,任何人都可以在 bbdd 的 init 中拥有自己的记录。

如果多个文件不可行,是否可以通过其他方式实现?

http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html

您可以使用 --fixture 标志加载特定的夹具文件: php app/console doctrine:fixtures:load --fixture=/src/BundleName/DataFixtures/ORM/Fixture.php

或者,您可以添加一个包含一些工作示例的 Fixtures.php.dist 文件,然后使用 .gitignore 忽略 Fixtures.php.

然后将命令添加到您的构建(或在作曲家脚本中),and/or您的文档以在检出项目时将此 .dist 文件复制到 Fixtures.php

如果您正在执行 BDD,另一种方法是创建一个 Helper class,可以在您的 Context 中使用它来创建和保留您在测试中需要的实体。这将允许您只创建测试所需的细节。它真正需要的只是 EntityManager,因此它可能比 pre-defining 前面的所有固定装置更简单。

您可以使用 Faker 生成逼真的实体。

class AbstractFixtureHelper implements ContainerAwareInterface
{
    /**
     * @var Generator
     */
    protected $faker;

    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct()
    {
        $this->faker = Factory::create();
    }

    /**
     * @param ContainerInterface|null $container
     * @return void
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * @return EntityManager
     */
    protected function getEntityManager()
    {
        return $this->container->get('doctrine.orm.entity_manager');
    }
}

然后对于不同的实体 - 在这个例子中,一个用户:

class UserFixtureHelper extends AbstractFixtureHelper
{
    public function createUser()
    {
        $user = new User();
        $user->setEmail($this->faker->email);
        $this->getEntityManager()->persist($user);
        $this->getEntityManager()->flush();

        return $user;
    }
}

然后在你的Context中,注入UserFixtureHelper,直接在场景步骤中创建。

/**
* @Given there is a User who XXX
*/
public function thereIsAUser()
{
    $user = $this->userFixtureHelper->createUser();
}