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

时间:2014-10-27 20:25:52

标签: symfony doctrine-orm

我在doctrine中添加了自定义选项:fixtures:load命令。现在我想知道如何在自定义fixture类中获得此命令选项:

class LoadUserData implements FixtureInterface, ContainerAwareInterface {

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

  }

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

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

因此,如果您已扩展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);
    }
}

然后在fixtures类中获取该容器参数。

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 :(得分:0)

执行函数不是为我调用的,我必须重命名命令调用:

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 

将调用您的个人执行功能。