Symfony featured image

Symfony get Environment[.env] variable in Service

In this tutorial I’ll show you how to pass environment variables from .env file to Custom Service in Symfony. There are basically 4 steps for this:

  1. Define the parameter in .env
  2. Configure parameter in Symfony configuration services.yaml
    • Pass as an argument in constructor of the service.
  3. Read receive parameters in constructor and assign to a local protected variable.
    • Use in the Service as you need.

Add Key value pair in .env file

In the .env file add a key value pair of parameter, ideally an UPPERCASE_CONVENTION is followed,

.env file is placed in the root of application.

 APP_CUSTOM_PARAM="This is custom env parameter"

Configure Parameter in services.yaml

In the second step we need to configure a mapping of this parameter in the Symfony. And further add them as arguments passed to the service registry where it could be accessed via constructor in the service.

In application-root/config/services.yaml file configure under parameters key.

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    app.custom_param: '%env(APP_CUSTOM_PARAM)%'

Further you need to register a service in the services.yaml under the services key.

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    app.custom_param: '%env(APP_CUSTOM_PARAM)%'


services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
            - '../src/Tests/'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller/'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones
    App\Service\YourCustomService:
        arguments:
            $customParam: '%app.custom_param%'

Receive in Constructor and Read value in Service

<?php


namespace App\Service;

use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;

class YourCustomService
{
    protected $em;
    protected $logger;
    protected $customParam;

    public function __construct(
        $customParam,
        LoggerInterface $logger,
        EntityManagerInterface $em,
    )
    {
        $this->customParam = $customParam;
        $this->em = $em;
        $this->logger = $logger;
    }

    public function yourFunctionHere()
    {
         //use your parameter the way you want $this->customParam;    
    }
}

Now you should be able to use the parameter the way you want, and you can easily pass multiple parameters in this way. when you are passing the custom parameter or environment variable you don’t need to bother about other services interfaces which are generally auto-wired by Symfony. You can see this process in above code as well.

If you are looking for accessing the variable in the Controller instead you can check out the tutorial for Reading environment(.env) variable in Symfony Controller.

Leave a Comment

Your email address will not be published. Required fields are marked *