How to get command argument outside command class?

2019-07-17 05:03发布

I added custom option to doctrine:fixtures:load command. Now I am wonder how to get this command option in custom fixtures class:

class LoadUserData implements FixtureInterface, ContainerAwareInterface {

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

  }

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

Any suggestions?

2条回答
再贱就再见
2楼-- · 2019-07-17 05:15

So if you have extended Doctrine\Bundle\FixturesBundle\Command\LoadDataFixturesDoctrineCommand and managed to add a additional argument, then you can set that value passed as a container parameter.

<?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);
    }
}

Then get that container parameter in your fixtures class.

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');

        ///....
    }
}
查看更多
Explosion°爆炸
3楼-- · 2019-07-17 05:33

The execute function is not call for me, i have to rename the command call:

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

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

on this way the command

php app/console app:fixtures:load 

will call your personal execute function.

查看更多
登录 后发表回答