Skip to content
Advertisement

How define some PHP constant in the Symfony configuration?

this is my first post, so i will try to be clear

So i need to define some constants in the Symfony configuration (in a .yaml file, i guess) I know i could define them throw public const MY_CONST but that is not what I want.

I guess this is what i need (the second part, i am not using Abstract controller as i am not in a controller)

https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters

But I just can’t get it to work. Could anyone help me, by giving me an exemple, or maybe an other way to do ?

Thanks guys.

Advertisement

Answer

The parameters you described can be used in the configuration defined as eg;

parameters:
    the_answer: 42

You can then use these values in further configuration things (see below for example). Or if you want to handle these values in a controller you can (not recommended anymore) use $this->getParameter('the_answer') to get the value.

Binding arguments (recommended):

This approach wil bind values which you can then get (auto-magically injected) in a controller function/service by referencing the argument.

The values can range from simple scalar values to services, .env variables, php constants and all of the other things the configuration can parse.

# config/services.yaml
services:
    _defaults:
        bind:
            string $helloWorld: 'Hello world!'  # simple string
            int $theAnswer: '%the_answer%'      # reference an already defined parameter.
            string $apiKey: '%env(REMOTE_API)%' # env variable.

Then these get injected in a service/controller function when we do something like:

public function hello(string $apiKey, int $theAnswer, string $helloWorld) {
    // do things with $apiKey, $theAnswer and $helloWorld
}

More details and examples can be found in the symfony docs https://symfony.com/doc/current/service_container.html#binding-arguments-by-name-or-type

Inject into service (alternative)

You can also directly inject it into the defined service using arguments.

# config/services.yaml
services:
    # explicitly configure the service
    AppUpdatesSiteUpdateManager:
        arguments:
            $adminEmail: 'manager@example.com'

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement