给出此配置命令:
protected function configure() {
$this->setName('command:test')
->addOption("service", null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, "What services are desired ?", array(
"s1" => true,
"s2" => true,
"s3" => true,
"s4" => false,
"s5" => true,
"s6" => true,
"s7" => true,
"s8" => true,
"s9" => true
))
}
现在调用命令时,如何传递关联数组。
#!/bin/bash
php app/console command:test --service s1:true --service s2:false --s3:true
条件:
if
答案 0 :(得分:3)
据我所知,使用命令选项时不可能(至少不像你所描述的那样......)。
最佳解决方法(IMO)使用命令参数(而不是命令选项)并编写额外代码(不是,放置所有额外代码并不好尽管可能在内部命令定义中。)
这将是这样的:
class TestCommand extends ContainerAwareCommand
{
protected function getDefaultServicesSettings()
{
return [
's1' => true,
's2' => true,
's3' => true,
's4' => false,
's5' => true,
's6' => true,
's7' => true,
's8' => true,
's9' => true
];
}
private function normalizeServicesValues($values)
{
if (!$values) {
return $this->getDefaultServicesSettings();
}
$new = [];
foreach ($values as $item) {
list($service, $value) = explode(':', $item);
$new[$service] = $value == 'true' ? true : false;
}
return array_merge($this->getDefaultServicesSettings(), $new);
}
protected function configure()
{
$this
->setName('commant:test')
->addArgument(
'services',
InputArgument::IS_ARRAY|InputArgument::OPTIONAL,
'What services are desired ?');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$services = $this->normalizeServicesValues(
$input->getArgument('services'));
// ...
}
}
然后
$ bin/console commant:test s1:false s9:false
在保留默认值的同时覆盖s1和s2值。