Symfony Console Component

repository·8.2·Indexed 27 days ago

https://github.com/symfony/console

A 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.

Tokens
2.9K
Snippets
3
Records
21
Agent score
95%

What's inside symfony/console

  1. Overview of the Console Component

    8.2
    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.
  2. Make a command lockable using LockableTrait

    8.2

    To prevent a command from running concurrently, you can use the LockableTrait within 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/lock component to use this feature:

    composer require symfony/lock

    Usage

    1. Use the LockableTrait in your command class.
    2. Call $this->lock($name, $blocking) inside your execute() method.
      • $name (optional): The name of the lock. If not provided, it defaults to the command name (from getName() or the #[AsCommand] attribute).
      • $blocking (optional): A boolean indicating whether the command should wait (block) until the lock is available. Defaults to false.
    3. If lock() returns false, the command is already running and you should exit.
    4. Call $this->release() to free the lock when the command finishes.
  3. Create a custom CLI command

    8.2

    To create a command in Symfony Console, extend the Symfony\Component\Console\Command\Command class. You must implement the execute() method, which contains the logic for your command. Alternatively, you can use setCode() 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.
  4. Map parameters to CLI arguments and options using Attributes

    8.2

    When 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;
    };
  5. Use the AsCommand attribute for command definition

    8.2

    Instead of calling setName(), setDescription(), etc., in configure(), you can use the Symfony\Component\Console\Attribute\AsCommand attribute 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)
  6. Use LazyCommand to improve CLI performance

    8.2

    The LazyCommand class 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 Command instance. The LazyCommand acts as a proxy, forwarding calls to the underlying command once it has been instantiated.

  7. Create an invokable command using a callable

    8.2
    You can define a Symfony command as a simple callable (like a closure or a function) instead of a full class. The InvokableCommand wrapper allows you to map function parameters directly to CLI arguments, options, or core Symfony utilities. The callable must return an int representing the exit status code.
  8. Configure command arguments and options

    8.2

    Within the configure() method of your command, use addArgument() and addOption() to define the input requirements.

    • addArgument(string $name, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): Adds a positional argument. Modes include InputArgument::REQUIRED or InputArgument::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., --force or -f).
  9. Define command metadata (Name, Description, Help, Aliases)

    8.2

    Use these methods to configure how the command appears in the CLI:

    • setName(string $name): Sets the command name (supports namespaces like foo: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.
  10. Set command exit codes

    8.2

    Commands should return an integer exit code from the execute() method. Use the following constants provided by the Command class:

    • 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;
  11. Use supported type hints for automatic parameter resolution

    8.2

    The InvokableCommand automatically injects the following objects into your callable if they are type-hinted:

    Type HintResolved Object
    InputInterfaceThe current input instance
    RawInputInterfaceThe current input instance
    OutputInterfaceThe current output instance
    SymfonyStyleA new SymfonyStyle instance
    CursorA new Cursor instance for output
    ApplicationThe command's application instance
    CommandThe command instance
    self (InvokableCommand)The InvokableCommand instance