2 Methods to Hide Console Command in Symfony 7

2 Methods to Hide Console Command in Symfony 7

By default, running bin/console or bin/console list shows a list of all console commands. However, there are cases where commands are designed to keep end-users unaware of them, such as commands for the legacy parts of the application or those intended solely for scheduled tasks. In such situations, we can define the command as hidden. This tutorial provides 2 methods how to hide console command in Symfony 7.

Method 1 - 'AsCommand' attribute with 'hidden'

The AsCommand attribute provides a convenient way to define console commands. To hide a command, you can use the hidden property within this attribute.

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

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

Now, the command app:test won't be displayed in the list of available commands when running php bin/console.

Hidden commands function similarly to regular commands, but they do not appear in command listings, ensuring end-users remain unaware of their existence.

Method 2 - 'isHidden' method

Another approach to hide a command is by implementing the isHidden method within the command class. This method should return a boolean value indicating whether the command should be hidden or not.

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

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

    public function isHidden(): bool
    {
        return true;
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.