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
JavaScript
x
PathToMyEventSubscriberTerminateSubscriber:
arguments:
- { param1: 'myvalue', param2: 'myvalue2' }
TerminateSubscriber.php:
JavaScript
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:
JavaScript
[
"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 :
JavaScript
PathToMyEventSubscriberTerminateSubscriber:
arguments: [ AppRepositoryMyRepository, [MyArray],"My String Value" ]
And in your construct:
JavaScript
/**
* @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;
}