gpt4 book ai didi

symfony - Symfony + Doctrine提供的特定于环境的数据固定装置

转载 作者:行者123 更新时间:2023-12-03 12:02:36 26 4
gpt4 key购买 nike

使用Smyfony2和Doctrin2,可以使用以下示例创建数据固定装置:http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html

我希望能够使用此概念进行测试,以便设置/拆卸可以创建用于功能测试的纯测试数据环境。如何在功能测试期间运行一组特定的仅测试夹具,以及如何将这些夹具与标准夹具分开,以便控制台命令忽略它们?

看来,解决方法是复制doctrine:fixtures控制台命令的功能并将测试装置存储在其他位置。有谁有更好的解决方案?

最佳答案

通过目录分解灯具的另一种方法是使用自定义灯具类。然后,您的灯具类将扩展该类,并指定将实际加载的环境。

<?php

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\KernelInterface;

/**
* Provides support for environment specific fixtures.
*
* This container aware, abstract data fixture is used to only allow loading in
* specific environments. The environments the data fixture will be loaded in is
* determined by the list of environment names returned by `getEnvironments()`.
*
* > The fixture will still be shown as having been loaded by the Doctrine
* > command, `doctrine:fixtures:load`, despite not having been actually
* > loaded.
*
* @author Kevin Herrera <kevin@herrera.io>
*/
abstract class AbstractDataFixture implements ContainerAwareInterface, FixtureInterface
{
/**
* The dependency injection container.
*
* @var ContainerInterface
*/
protected $container;

/**
* {@inheritDoc}
*/
public function load(ObjectManager $manager)
{
/** @var KernelInterface $kernel */
$kernel = $this->container->get('kernel');

if (in_array($kernel->getEnvironment(), $this->getEnvironments())) {
$this->doLoad($manager);
}
}

/**
* {@inheritDoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}

/**
* Performs the actual fixtures loading.
*
* @see \Doctrine\Common\DataFixtures\FixtureInterface::load()
*
* @param ObjectManager $manager The object manager.
*/
abstract protected function doLoad(ObjectManager $manager);

/**
* Returns the environments the fixtures may be loaded in.
*
* @return array The name of the environments.
*/
abstract protected function getEnvironments();
}

您的灯具最终看起来像这样:
<?php

namespace Vendor\Bundle\ExampleBundle\DataFixtures\ORM;

use AbstractDataFixture;
use Doctrine\Common\Persistence\ObjectManager;

/**
* Loads data only on "prod".
*/
class ExampleData extends AbstractDataFixture
{
/**
* @override
*/
protected function doLoad(ObjectManager $manager)
{
// ... snip ...
}

/**
* @override
*/
protected function getEnvironments()
{
return array('prod');
}
}

我相信这应该同时适用于两个ORM和ODM数据装置。

关于symfony - Symfony + Doctrine提供的特定于环境的数据固定装置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11817971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com