代码之家  ›  专栏  ›  技术社区  ›  eldiablo62

Symfony为不同的环境(prod、test、dev)使用不同的条令夹具

  •  0
  • eldiablo62  · 技术社区  · 6 年前

    嗨,我有一个关于使用datafixture的问题,我想在prod,dev,test环境中使用fixture。我试过使用 --fixtures 如何在命令行中加载所需文件?

    有没有可能用 --env 选择 doctrine:fixtures:load 命令?

    • 应用程序/数据装置/产品
    • 应用程序/数据装置/开发
    • 应用程序/数据装置/测试

    我用的是symfony3.4 谢谢你的帮助

    1 回复  |  直到 6 年前
        1
  •  2
  •   Community CDub    5 年前

    不幸的是 --fixtures 选项在DoctrineFixturesBundle 3.0中已被删除,该问题即将用另一种方法解决 approach

    我建议当时要有点耐心。

    :如何使用环境来解决此问题:

    正如您在评论中所提到的,您确实可以使用env选项来解决以下问题:

    namespace App\DataFixtures;
    
    use Doctrine\Common\DataFixtures\FixtureInterface;
    use Doctrine\Common\Persistence\ObjectManager;
    use Symfony\Component\DependencyInjection\ContainerAwareInterface;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    abstract class AbstractFixture implements ContainerAwareInterface, FixtureInterface
    {
        protected $container;
    
        public function setContainer(ContainerInterface $container = null)
        {
            $this->container = $container;
        }
    
        public function load(ObjectManager $manager)
        {
        
            $kernel = $this->container->get('kernel');
    
            if (in_array($kernel->getEnvironment(), $this->getEnvironments())) {
                $this->doLoad($manager);
            }
        }
    
        abstract protected function doLoad(ObjectManager $manager);
    
        abstract protected function getEnvironments();
    }
    

    然后您应该使用a类为每个环境(prod、test、dev)扩展这个抽象Fixture类,如下所示(仅为prod显示的示例):

    namespace App\DataFixtures;
    
    use Doctrine\Common\Persistence\ObjectManager;
    
    class ProdFixture extends AbstractFixture
    {
    
        protected function doLoad(ObjectManager $manager)
        {
            // load what you need to load for prod environment 
        }
    
        protected function getEnvironments()
        {
            return ['prod'];
        }
     }
    

    ProdFixture , TestFixture , DevFixture

    每次运行 doctrine:fixtures:load 命令 --env