mlwacosmos
mlwacosmos

Reputation: 4561

Access parameter from the Command Class

I am adding a new command line. I would like to have access to the value of a parameter (parameters.yml) in my Class.

I read that i should add this class as a service to have access to the parameter. So

//config.yml

imports:
- { resource: services.yml }

//services.yml

services:
  less_css_compiler:
    class: MyVendor\MyBundle\Command\ThemeCommand
    arguments: [%less_compiler%]

//parameters.yml

parameters:
    less_compiler:     WinLess.exe

it is said that normaly the argument is in the constructor of the class but if I do this :

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

I have a warning saying that the first argument is missing. In the Command mother class there is a name as then unique argument of the constructor but even though I write :

 public function __construct($name, $less_compiler) {
 }

It does not change anything..

Other possibility is to call the service inside my class :

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

But how do I get the argument ?

Thank you

Upvotes: 31

Views: 28873

Answers (2)

Strabek
Strabek

Reputation: 2511

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');
        // ...
    }
}

Upvotes: 25

Venu
Venu

Reputation: 7289

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.

Upvotes: 41

Related Questions