Access parameter from the Command Class Access parameter from the Command Class symfony symfony

Access parameter from the Command Class


Simple way, let command extend ContainerAwareCommand

$this->getContainer()->getParameter('parameter_name');

or

You should create seperate service class

$service = $this->getContainer()->get('less_css_compiler');

//services.yml

services:  less_css_compiler:    class: MyVendor\MyBundle\Service\LessCompiler    arguments: [%less_compiler%]

In service class, create constructor like above you mentioned

public function __construct($less_compiler) {    $this->less_compiler = $less_compiler;}

Call the service from command class.

Thats it.

Reason: You are making command class itself as service, bit command class contructor expects the command name as the first argument.


I had the same problem when using Symfony 4.4. This blog post explains it very well.If you use autowire just update your code as below:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;class MessageGenerator{    private $params;    public function __construct(ParameterBagInterface $params)    {        $this->params = $params;    }    public function someMethod()    {        $parameterValue = $this->params->get('parameter_name');        // ...    }}