Symfony Console Component
repository·8.2·Indexed 27 days ago
https://github.com/symfony/consoleA PHP library for creating command-line interfaces (CLIs). It provides a framework for defining commands by extending the Command class or using invokable callables, handling input/output formatting, and managing arguments and options. Key features include the AsCommand attribute for metadata, LazyCommand for performance optimization, LockableTrait for preventing concurrent execution, and support for shell autocompletion in bash, zsh, and fish.
What's inside symfony/console
- The Symfony Console component provides tools to create beautiful and testable command-line interfaces (CLIs). It allows you to define commands, handle input/output, and manage complex CLI interactions.
Make a command lockable using LockableTrait
8.2To prevent a command from running concurrently, you can use the
LockableTraitwithin your command class. This trait provides mechanisms to acquire and release a lock based on the command's name.Requirements You must install the
symfony/lockcomponent to use this feature:composer require symfony/lockUsage
- Use the
LockableTraitin your command class. - Call
$this->lock($name, $blocking)inside yourexecute()method.$name(optional): The name of the lock. If not provided, it defaults to the command name (fromgetName()or the#[AsCommand]attribute).$blocking(optional): A boolean indicating whether the command should wait (block) until the lock is available. Defaults tofalse.
- If
lock()returnsfalse, the command is already running and you should exit. - Call
$this->release()to free the lock when the command finishes.
- Use the
Create a custom CLI command
8.2To create a command in Symfony Console, extend the
Symfony\Component\Console\Command\Commandclass. You must implement theexecute()method, which contains the logic for your command. Alternatively, you can usesetCode()to pass a callable that handles the execution.Common lifecycle methods you can override:
configure(): Define the command's name, description, help, arguments, and options.interact(): Interact with the user (e.g., asking for missing arguments) before the input is validated.initialize(): Initialize the command after input is bound but before validation.execute(): The main logic of the command. It must return an integer exit code.
Map parameters to CLI arguments and options using Attributes
8.2When using an invokable command, you can use specific attributes on your function parameters to automatically configure the command's
InputDefinition:Argument: Defines a CLI argument.Option: Defines a CLI option.MapInput: Maps a group of arguments and options to a single parameter.
Additionally, the command automatically resolves several core Symfony types based on their type hints.
use Symfony\Component\Console\Attribute\Argument; use Symfony\Component\Console\Attribute\Option; use Symfony\Component\Console\Attribute\MapInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; $invokable = function ( InputInterface $input, OutputInterface $output, #[Argument] string $username, #[Option] bool $force = false ): int { // ... return 0; };Use the AsCommand attribute for command definition
8.2Instead of calling
setName(),setDescription(), etc., inconfigure(), you can use theSymfony\Component\Console\Attribute\AsCommandattribute on your class. This is often preferred for performance and clarity.Supported attribute properties:
name: The command name.description: The command description.aliases: An array of aliases.pass_options: (Implicitly handled via the attribute structure)
Use LazyCommand to improve CLI performance
8.2The
LazyCommandclass allows you to defer the instantiation of a command until it is actually needed (e.g., when it is executed). This is particularly useful in large applications with many commands to reduce the overhead of bootstrapping every command on every CLI invocation.To use it, you provide a factory closure that returns the actual
Commandinstance. TheLazyCommandacts as a proxy, forwarding calls to the underlying command once it has been instantiated.Create an invokable command using a callable
8.2You can define a Symfony command as a simple callable (like a closure or a function) instead of a full class. TheInvokableCommandwrapper allows you to map function parameters directly to CLI arguments, options, or core Symfony utilities. The callable must return anintrepresenting the exit status code.Configure command arguments and options
8.2Within the
configure()method of your command, useaddArgument()andaddOption()to define the input requirements.addArgument(string $name, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): Adds a positional argument. Modes includeInputArgument::REQUIREDorInputArgument::OPTIONAL.addOption(string $name, string|array|null $shortcut = null, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): Adds an option (e.g.,--forceor-f).
Define command metadata (Name, Description, Help, Aliases)
8.2Use these methods to configure how the command appears in the CLI:
setName(string $name): Sets the command name (supports namespaces likefoo:bar).setDescription(string $description): A short summary of what the command does.setHelp(string $help): Detailed help text shown when running the command with--help.setAliases(iterable $aliases): Sets alternative names for the command.setHidden(bool $hidden): Hides the command from the list of available commands.
Set command exit codes
8.2Commands should return an integer exit code from the
execute()method. Use the following constants provided by theCommandclass:Command::SUCCESS(0): Everything went fine.Command::FAILURE(1): A general error occurred.Command::INVALID(2): Incorrect usage or invalid input.
public const SUCCESS = 0; public const FAILURE = 1; public const INVALID = 2;Use supported type hints for automatic parameter resolution
8.2The
InvokableCommandautomatically injects the following objects into your callable if they are type-hinted:Type Hint Resolved Object InputInterfaceThe current input instance RawInputInterfaceThe current input instance OutputInterfaceThe current output instance SymfonyStyleA new SymfonyStyleinstanceCursorA new Cursorinstance for outputApplicationThe command's application instance CommandThe command instance self(InvokableCommand)The InvokableCommandinstanceReference: list command options and arguments
8.2Thelistcommand supports the following arguments and options: