按目录拆分fixture 的另一种方法是使用自定义fixture 类。然后,您的夹具类将扩展此类并指定实际加载它的环境。
<?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 数据夹具。