Search code examples
symfonysymfony4

symfony4 use .env config variables in a service


I am using a package that is not especially made for symfony (TNTsearch), and have put all the functions I want to use in a service I called TNTsearchHelper.php. This service requires some variables, including some that could be found in the .env file. I currently define and construct these in my class:

class TntSearchHelper
{
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;

        $config = [
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'databasename',
            'username'  => 'user',
            'password'  => 'pw',
            'storage'   => 'my/path/to/file',
            'charset'   => 'utf8',
            'collation' => 'utf8_general_ci',
        ];

        $this->config = $config;
    }

What I would really like is to simply use the variables for my database that are set in the .env file. Is there any way to do this? This service is not registered in services.yaml because this is not neccesary with the autowire: true option, so I don't have any config options/file for my service in the config and wonder if I can keep it that way.


Solution

  • Yes. It's possible. If you want to use env variables for configuration, you have two options:

    1.Use getenv:

    $config = [
        'driver'    => 'mysql',
        'host'      => getenv('MYSQL_HOST'),
        'database'  => getenv('MYSQL_DB'),
        'username'  => getenv('MYSQL_LOGIN'),
        'password'  => getenv('MYSQL_PASSWORD'),
        'storage'   => 'my/path/to/file',
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
    ];
    

    2.Configure your service in services.yaml:

    services:
      App\TntSearchHelper:
        arguments:
          - '%env(MYSQL_HOST)%'
          - '%env(MYSQL_DB)%'
          - '%env(MYSQL_LOGIN)%'
          - '%env(MYSQL_PASSWORD)%'
    

    And change your __construct function to this:

    public function __construct(string $host, string $db, string $login, string $password, EntityManagerInterface $em) 
    {
        $this->em = $em;
        $config = [
            'driver'    => 'mysql',
            'host'      => $host,
            'database'  => $db,
            'username'  => $login,
            'password'  => $password,
            'storage'   => 'my/path/to/file',
            'charset'   => 'utf8',
            'collation' => 'utf8_general_ci',
        ];
        $this->config = $config;
    }
    

    Also make sure that all this env variables are set because there's only DATABASE_URL variable in .env file by default