Symfony provides flexible tools for building modern applications, and one common requirement is controlling which routes are accessible in different environments. For example, you may want certain routes to exist only in development or testing while keeping them completely unavailable in production. This helps avoid exposing debug pages, internal tools, or experimental features to end users. This tutorial shows how to make a route available in a specific environment in a Symfony 8 application.
Symfony determines the current environment using the APP_ENV variable, which is configurable through the .env file.
.env
APP_ENV=dev
When defining routes with PHP attributes, Symfony allows you to specify an environment directly on the Route attribute using the env option. This ensures the route is registered only when the application runs in the matching environment.
If you prefer defining routes in YAML files, Symfony also supports environment-based conditions using the when@ENV section.
src/Controller/TestController.php
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
#[Route('/', env: 'dev')]
public function index(): Response
{
return new Response();
}
}
config/routes.yaml
when@dev:
test_index:
path: /
controller: App\Controller\TestController::index
Sometimes a route should be available in more than one environment, such as both development and testing. When using attributes, you can easily define multiple environments using an array.
src/Controller/TestController.php
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
#[Route('/', env: ['dev', 'test'])]
public function index(): Response
{
return new Response();
}
}
Leave a Comment
Cancel reply