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.
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.
<?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.
<?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.
<?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.
{{ app.environment }}
<?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