Make Console Command Available in Specific Environment in Symfony 7

Make Console Command Available in Specific Environment in Symfony 7

Symfony brings powerful features and improvements to web development, and managing console commands efficiently is a crucial aspect of any Symfony application. In certain scenarios, you may want to limit the availability of a console command to specific environments, such as development or testing, to prevent accidental execution in production. This tutorial explains how to make console command available in specific environment in Symfony 7.

The APP_ENV variable, configurable through the .env file, enables us to define the specific environment in which the application operates.

.env

APP_ENV=dev

The When attribute can be used to register services in some environments. For example, in the following code, we created a console command which only be available when the application is running in the dev (development) environment.

<?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\When;

#[When('dev')]
#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        return Command::SUCCESS;
    }
}

We can also specify multiple When attributes to enable the availability of the console command in various environments, such as dev and test.

Leave a Comment

Cancel reply

Your email address will not be published.