Make Console Command Available in Specific Environment in Symfony 8

Make Console Command Available in Specific Environment in Symfony 8

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 the console command available in a specific environment in Symfony 8.

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 that will only be available when the application is running in the dev (development) environment.

src/Command/TestCommand.php

<?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 self::SUCCESS;
    }
}

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

If the goal is to make a console command available everywhere except one environment, Symfony offers the WhenNot attribute. For example, we created a console command that is excluded from the prod environment and available in other environments.

src/Command/TestCommand.php

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

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

Just like When, the WhenNot attribute can be repeated to exclude from more than one environment.

Leave a Comment

Cancel reply

Your email address will not be published.