如何从下面的类中的yml文件中获取参数,以便我可以使用CLI打印它?
错误:
mbp:symfony em$ app/console phing:report
PHP Fatal error: Call to undefined method Site\CommonBundle\Command\GreetCommand::getParameter() in symfony/src/Site/CommonBundle/Command/GreetCommand.php on line 25
的symfony / SRC /站点/ CommonBundle /命令/ GreetCommand.php
namespace Site\CommonBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class GreetCommand extends ContainerAwareCommand
{
public function __construct()
{
parent::__construct();
}
protected function configure()
{
$this->setName('phing:report');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$user = $this->getParameter('dummy_user');
$output->writeln($user['admin']['username']);
}
}
symfony的/应用/配置/ globals_dev.yml
#Site globals
parameters:
dummy_user:
admin:
username: admin
superadmin:
username: superadmin
答案 0 :(得分:2)
如果你的目标只是从容器中获取参数,你可以从CLI访问它:
$this->getContainer()->getParameter('dummy_user');
答案 1 :(得分:0)
在Symfony 4.3或更高版本中,您可以使用ContainerBagInterface一次注入所有应用程序参数,然后访问您的参数:
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
class TestCommand extends Command
{
public function __construct(ContainerBagInterface $params)
{
$this->params = $params;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$yourParam = $this->params->get('hereYourParam');
}
}
请参阅:https://symfony.com/doc/master/configuration.html#accessing-configuration-parameters
这种方法对于在服务中注入所有参数是有效的,但在控制台命令中也可以使用。