我的控制檯命令有兩個選項(不是參數)。如何設置控制檯命令的選項
這是我的命令代碼
class crawlerCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('top:crawler')
->setDescription('Greet someone')
->addOption('opt1', null, InputOption::VALUE_REQUIRED, 'option1')
->addOption('opt2',null, InputOption::VALUE_OPTIONAL, 'option2');
然後我試圖調用命令,從控制器
例如我想從控制器做這個控制檯命令
$ app/console top:crawler --opt1=s --opt2=2
因此我做了這個代碼。
public function indexAction(){
$command = $this->get('crawlerCommandService');
$inputDefinition = new InputDefinition(array(
new InputOption('opt1', 's', InputOption::VALUE_OPTIONAL),
new InputOption('opt2', '2', InputOption::VALUE_OPTIONAL),
));
$input = new ArgvInput(array('argv' => 'app'));
$input->bind($inputDefinition);
$output = new ConsoleOutput();
$returnCode = $command->run($input, $output);
但它不起作用。
請給出一些提示。
我可以使用ArrayInput而不是ArgvInput來解決問題。
我在這裏寫下代碼。
$command = $this->get('crawlerCommandService');
$output = new ConsoleOutput();
$arguments = array(
'--opt1' => 's',
'--opt2' => '2'
);
$input = new ArrayInput($arguments);
$returnCode = $command->run($input, $output);
調用該命令有什麼好處?當然,如果你想重複邏輯,那麼你可以將所有這些都放在一個服務中,然後你可以單獨調用。據我所知,命令只是另一種觀點。 – qooplmao