Get Environment Name in Symfony 7

Get Environment Name in Symfony 7

By default, Symfony application has three environments: dev for local development, prod for production servers and test for running automated tests. This tutorial explains how to get environment name in Symfony 7 application.

The APP_ENV variable defines the environment in which the application runs. This variable can be specified in the .env file.

.env

APP_ENV=dev

We can get environment name in different parts of the application.

Controller - Method 1

If controller extends AbstractController class, the getParameter method can be used to get kernel.environment parameter from container.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        $env = $this->getParameter('kernel.environment');

        return new Response($env);
    }
}

Controller - Method 2

If the controller does not extend the base controller, we can use the Autowire attribute to inject the value of the kernel.environment parameter into the constructor property.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    public function __construct(#[Autowire('%kernel.environment%')] private string $env)
    {
    }

    #[Route('/')]
    public function index(): Response
    {
        return new Response($this->env);
    }
}

Note: don't forget to clear cache manually in prod environment.

Service

To get the environment name in the service, we can inject the value of the kernel.environment parameter into the constructor property by using the Autowire attribute.

src/Service/TestService.php

<?php

namespace App\Service;

use Symfony\Component\DependencyInjection\Attribute\Autowire;

class TestService
{
    public function __construct(#[Autowire('%kernel.environment%')] private string $env)
    {
    }
}

Template

The global app variable can be used in the Twig template. This variable provides access to the app.environment variable.

templates/test/index.html.twig

{{ app.environment }}

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        return $this->render('test/index.html.twig');
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.