Skip to content
Advertisement

Symfony inject array through services.yaml

I am trying to inject an array to Event Subscriber, but I also inject an other repository so I don’t know how this will work:

Here’s what I am trying:

services.yaml

PathToMyEventSubscriberTerminateSubscriber:
    arguments:
        - { param1: 'myvalue', param2: 'myvalue2' }

TerminateSubscriber.php:

private Repository $repo;
/** @var array<string, string>  */
private array $config;

public function __construct(Repository $repo, array $config = [])
{
    $this->repo = $repo;
    $this->config = $config;
}

It says that the first parameter should be an instance of the Repo, array given. But if I switch the parameters it says “optional parameter given before required”

EDIT

The array should look like this:

[
  "a" => [400],
  "b" => [400, 500],
]

Advertisement

Answer

You are very close but you need some changes in your code. If you need to pass a Repository, array or string from service to class you need to pass it like this.

In service.yaml :

PathToMyEventSubscriberTerminateSubscriber:
  arguments: [ AppRepositoryMyRepository, [MyArray],"My String Value" ]

And in your construct:

/**
 * @param Repository $repo
 * @param array $config 
 * @param string $stringValue
 */
public function __construct(Repository $repo, array $config = [], string $stringValue)
{
    $this->repo = $repo;
    $this->config = $config;
    $this->string = $string;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement