Symfony framework has a debug mode that helps to debug application during development. This tutorial explains how to check if debug mode is enabled in Symfony 7 application.
We can specify the APP_ENV
variable in the .env
file. This variable defines the environment in which the application runs. By default, in the dev
and test
environments, debug mode is enabled and in the prod
environment is disabled.
APP_ENV=dev
Debug mode could be enabled or disabled by using a separate APP_DEBUG
environment variable. Its value can be 1
or 0
.
APP_ENV=dev
APP_DEBUG=0
We can check debug mode in different parts of the application.
Controller - Method 1
If controller extends the AbstractController
class, we can use the getParameter
method to retrieve kernel.debug
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
{
$debug = $this->getParameter('kernel.debug');
return new Response($debug ? 'Enabled' : 'Disabled');
}
}
Controller - Method 2
If your controller does not extend the base controller, you can inject the value of the kernel.debug
parameter in the controller.
services:
# ...
App\Controller\TestController:
tags: ['controller.service_arguments']
arguments: ['%kernel.debug%']
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
public function __construct(private bool $debug)
{
}
#[Route('/')]
public function index(): Response
{
return new Response($this->debug ? 'Enabled' : 'Disabled');
}
}
Note: don't forget to clear cache manually if debug mode is disabled.
Service
If we want to determine debug mode in the service, we can inject the value of the kernel.debug
parameter.
services:
# ...
App\Service\TestService:
arguments: ['%kernel.debug%']
<?php
namespace App\Service;
class TestService
{
public function __construct(private bool $debug)
{
}
}
Template
In the Twig template, we can use the global app
variable. It gives access to the app.debug
variable.
{{ app.debug ? 'Enabled' : 'Disabled' }}
<?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