Wednesday, August 23, 2017

Symfony 3.2 brings support of PHP constants in YAML

A nice improvement of Symfony 3.2 is support of PHP constants in YAML files.

This allows to define a service from a class and some constructor parameters defined as PHP constants, all in a services.yml file (no PHP code involved, just inject it !).

Let's try it with a PSR-7 HTTP client :

    services:

        # Concrete implementation of HTTP client
        app.api_client.http_client:
            class: Http\Client\Curl\Client
            arguments:
                - "@app.api_client.message_factory"
                - "@app.api_client.stream_factory"
                - !php/const:CURLOPT_CONNECTTIMEOUT: 4
                  !php/const:CURLOPT_TIMEOUT: 10
        # Concrete implementation of message factory
        app.api_client.message_factory:
            class: Http\Message\MessageFactory\GuzzleMessageFactory
        # Concrete implementation of stream factory
        app.api_client.stream_factory:
            class: Http\Message\StreamFactory\GuzzleStreamFactory

        # Use the fully YAML configured HttpClient in your service !
        app.api_client:
            class: App\Api\Client
            arguments:
                - "@app.api_client.http_client"
                ...

This example is based on PHP-HTTP PSR7 compliant library and documentation (http://php-http.readthedocs.io/en/latest/clients/curl-client.html)