Make Console Command Available if Debug Mode is Enabled in Symfony 7

Make Console Command Available if Debug Mode is Enabled in Symfony 7

Symfony provides a robust foundation for developing web applications. One of its notable features is the Console component, which allows developers to create and run commands. By default, all commands are available in both production and development environments. However, in some cases, you might want to restrict certain commands to only be available when the application is running in debug mode. This ensures that sensitive or potentially risky commands are not accidentally executed in a production environment. This tutorial shows how to make console command available if debug mode is enabled in Symfony 7.

The .env file allows us to set the APP_ENV variable, which serves to specify the environment in which the application operates.

.env

APP_ENV=dev

Typically, debug mode is enabled in the dev and test environments, while it is disabled in the prod environment.

The isEnabled method is crucial for determining whether the command should be available. In this example, it simply returns the value of the debug property, making the command available only when the application is in debug mode.

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
    public function __construct(#[Autowire('%kernel.debug%')] private bool $debug)
    {
        parent::__construct();
    }

    public function isEnabled(): bool
    {
        return $this->debug;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        return Command::SUCCESS;
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.