Environment specific data fixtures with Symfony+Doctrine

前端 未结 2 891
失恋的感觉
失恋的感觉 2021-01-31 19:07

With Smyfony2 and Doctrin2, data fixtures can be created using the following example: http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html

What I wou

2条回答
  •  耶瑟儿~
    2021-01-31 19:57

    An alternative to breaking out fixtures by directory is to use a custom fixture class. Your fixture classes would then extend this class and specify the environments it will actually be loaded in.

     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 
     */
    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();
    }
    

    Your fixtures would end up looking like this:

    I believe that this should work with both ORM an ODM data fixtures.

提交回复
热议问题