如何在命令类之外获得命令参数?

问题描述:

我将自定义选项添加到doctrine:fixtures:load命令。现在我想知道如何在定制灯具类中得到这个命令选项:如何在命令类之外获得命令参数?

class LoadUserData implements FixtureInterface, ContainerAwareInterface { 

    private $container; 
    /** 
    * {@inheritDoc} 
    */ 
    public function load(ObjectManager $manager) { 

    } 

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

有什么建议吗?

所以,如果你扩展了Doctrine\Bundle\FixturesBundle\Command\LoadDataFixturesDoctrineCommand并设法添加一个额外的参数,那么你可以设置该值作为容器参数传递。

<?php 

namespace Your\Bundle\Command; 

use Symfony\Component\Console\Input\InputInterface; 
use Symfony\Component\Console\Output\OutputInterface; 
use Doctrine\Bundle\FixturesBundle\Command\LoadDataFixturesDoctrineCommand; 

class LoadDataFixturesCommand extends LoadDataFixturesDoctrineCommand 
{ 
    /** 
    * {@inheritDoc} 
    */ 
    protected function configure() 
    { 
     parent::configure(); 

     $this->addOption('custom-option', null, InputOption::VALUE_OPTIONAL, 'Your Custom Option'); 
    } 

    /** 
    * {@inheritDoc} 
    */ 
    protected function execute(InputInterface $input, OutputInterface $output) 
    { 
     $this->getContainer()->setParameter('custom-option', $input->getOption('custom-option')); 

     parent::execute($input, $output); 
    } 
} 

然后在您的灯具类中获取该容器参数。

class LoadUserData implements FixtureInterface, ContainerAwareInterface 
{ 
    /** 
    * If you have PHP 5.4 or greater, you can use this trait to implement ContainerAwareInterface 
    * 
    * @link https://github.com/symfony/symfony/blob/master/src/Symfony/Component/DependencyInjection/ContainerAwareTrait.php 
    */ 
    use \Symfony\Component\DependencyInjection\ContainerAwareTrait; 

    /** 
    * {@inheritDoc} 
    */ 
    public function load(ObjectManager $manager) 
    { 
     $customOption = $this->container->getParameter('custom-option'); 

     ///.... 
    } 
} 
+1

这将是实际夹具中的' - > getParameter('fixture-option')'。 – qooplmao 2014-10-28 13:53:30

+0

@Qoop哎呀,谢谢你指出。编辑。 :) – 2014-10-28 15:44:57

执行功能不是叫我,我不得不重新命名命令调用:

protected function configure() 
{ 
    parent::configure(); 

    $this->setName('app:fixtures:load') 
     ->addOption('custom-option', null, InputOption::VALUE_OPTIONAL, 'Your Custom Option'); 
} 
在这条路上

命令

php app/console app:fixtures:load 

会打电话给您的个人执行功能。