Reputation: 12740
How can I get parameters from a yml file in class below so that I can print it with CLI?
Error:
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/Site/CommonBundle/Command/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/app/config/globals_dev.yml
#Site globals
parameters:
dummy_user:
admin:
username: admin
superadmin:
username: superadmin
Upvotes: 1
Views: 436
Reputation: 2349
In Symfony 4.3 or above you can inject all the application parameters at once with the ContainerBagInterface and then access to your parameter:
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');
}
}
See: https://symfony.com/doc/master/configuration.html#accessing-configuration-parameters
This approach is valid for inject all parameters in a services but it works also in a Console command.
Upvotes: 0
Reputation: 1057
If your goal is to simply get a parameter from the container, you can access it like this from the CLI:
$this->getContainer()->getParameter('dummy_user');
Upvotes: 2