dev0
dev0

Reputation: 1057

Accessing Symfony parameters from Service

I have written a service which uses guzzle to make a request to another site. The guzzle parameters (URL, headers etc.) must be configurable, so I have stored them in app/config/parameters.yml

But as the service does not have access to the container, how can I retrieve the parameters?

Upvotes: 0

Views: 699

Answers (1)

miikes
miikes

Reputation: 984

  1. If you don't want to pass many parameters to constructor,

a) you can pass many parameters as array.

parameters:
    my_params:
         foo: bar
         baz: 1

services:
    app.my_service:
    class: \yourservice\
    arguments:
        - '%my_params%'

b) you can use setters

services:
    app.my_service:
        class: \yourservice\
        calls:
            - [setParameterA, ['%first_param%']]
            - [setParameterB, ['%second_param%']]
            - ...    
  1. For your case is better to create Guzzle Client from Factory with given params. You can define many various clients and inject the specific one into your service.

`

services:
    app.client_factory:
        class: AppBundle\Service\ClientFactory

    app.some_client:
        class: GuzzleHttp\Client
        factory: 'app.client_factory:create'
        arguments:
            - []
            -
              base_uri: '%url%/%version%'
              headers:
                  User-Agent: 'MyAgent 0.1'
                  Accept: 'application/json'
                  content-type: 'application/json'
            - ~

    app.my_service:
        class: \yourservice\
        arguments:
            - '@app.some_client'

Upvotes: 1

Related Questions