How to inject an array of parameters in symfony service?

by darrion.kuhn , in category: PHP Frameworks , a month ago

How to inject an array of parameters in symfony service?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , a month ago

@darrion.kuhn 

To inject an array of parameters in a Symfony service, you can follow these steps:

  1. Define the parameters in your services.yaml file or any other configuration file.
1
2
3
4
5
6
# services.yaml
parameters:
    my_array_parameter:
        - value1
        - value2
        - value3


  1. Define the service and use the % syntax to refer to the array parameter.
1
2
3
4
5
# services.yaml
services:
    AppServiceMyService:
        arguments:
            - '%my_array_parameter%'


  1. In your service class, declare a constructor and use the parameter as an argument.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// src/Service/MyService.php
namespace AppService;

class MyService
{
    private $myArray;

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

    // ...
}


  1. Symfony's autowiring feature will automatically inject the array parameter into the service when it is instantiated. You can now use the $myArray property in your service class.


Note: If you want to inject the array parameter into a non-service class, you can use the container service to retrieve the values from the container.

1
$myArray = $container->getParameter('my_array_parameter');


Make sure to replace AppServiceMyService and my_array_parameter with your own service class and parameter name accordingly.