The `symfony/console` component is a powerful PHP library provided by the Symfony project, designed for building robust and user-friendly command-line interfaces (CLIs). It allows developers to create custom console commands that can be executed from the terminal, automating tasks, performing data migrations, generating code, running cron jobs, or any other scriptable operation.
Key Concepts and Features:
1. Application: The central entry point for your console application. It manages the registration and execution of all commands. You instantiate an `Application` object, add your commands to it, and then call its `run()` method.
2. Command: The fundamental building block of any console application. Each command is a separate class that extends `Symfony\Component\Console\Command\Command`. A command defines its name, description, arguments, options, and the logic to be executed.
3. Input (InputInterface): Represents the command-line input. It provides methods to retrieve arguments (positional values) and options (flags or key-value pairs) passed to the command. Examples include `getArgument()` and `getOption()`.
4. Output (OutputInterface): Handles writing information back to the console. It supports different verbosity levels (quiet, normal, verbose, very verbose, debug) and allows for formatted output, including colors, progress bars, tables, and more. Common methods include `writeln()`, `write()`, and various helpers.
5. Arguments and Options:
* Arguments: Required or optional positional values passed to the command (e.g., `php bin/console app:greet John`). Defined using `addArgument()`.
* Options: Optional flags or key-value pairs that modify a command's behavior (e.g., `php bin/console app:greet --yell`). Defined using `addOption()`.
6. Helper Sets: Provides pre-built helpers for common CLI tasks, such as asking questions (`QuestionHelper`), displaying progress bars (`ProgressBar`), or formatting tables (`Table`). The `SymfonyStyle` helper wraps many of these for a consistent look and feel.
7. Life Cycle: A typical command's life cycle involves:
* `configure()`: Where you define the command's name, description, arguments, and options.
* `initialize()`: (Optional) Used to initialize properties or perform setup before `interact()` and `execute()`.
* `interact()`: (Optional) Allows you to interact with the user before `execute()` to prompt for missing arguments/options.
* `execute()`: Contains the main logic of the command, using `InputInterface` to read input and `OutputInterface` to write output.
`symfony/console` is highly extensible, testable, and promotes clean code separation for command-line tasks, making it a cornerstone for many PHP projects, especially those built with the Symfony Framework.
Example Code
```php
<?php
// bin/console (or app.php - your main console application entry point)
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Console\Application;
use App\Command\GreetCommand;
// Create a new console application
$application = new Application('My Awesome Console App', '1.0.0');
// Add your custom commands to the application
$application->add(new GreetCommand());
// Run the application (this will parse arguments and execute the selected command)
$application->run();
// src/Command/GreetCommand.php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
class GreetCommand extends Command
{
// Define the command's name (how it's called from the terminal)
protected static $defaultName = 'app:greet';
// Define a short description for the command
protected static $defaultDescription = 'Greets a user by name';
protected function configure(): void
{
$this
->setDescription(self::$defaultDescription)
->setHelp('This command allows you to greet a user by providing their name and an optional --yell flag.')
// Add an argument: 'name', optional, with a default value
->addArgument('name', InputArgument::OPTIONAL, 'Who do you want to greet?', 'World')
// Add an option: 'yell', no shortcut, no value required (it's a flag)
->addOption('yell', 'y', InputOption::VALUE_NONE, 'If set, the message will be yelled (uppercase)');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
// SymfonyStyle provides a lot of helpers for consistent and styled output
$io = new SymfonyStyle($input, $output);
// Get the 'name' argument value
$name = $input->getArgument('name');
// Get the 'yell' option value (true if present, false otherwise)
$shouldYell = $input->getOption('yell');
// Build the greeting message
$message = sprintf('Hello, %s!', $name);
if ($shouldYell) {
$message = strtoupper($message);
$io->warning('YELLING MODE ACTIVATED!');
}
// Output the greeting message using a success style
$io->success($message);
// You can also use the raw OutputInterface for more control:
// $output->writeln(sprintf('<info>Greeting: %s</info>', $message));
// Return Command::SUCCESS to indicate successful execution
return Command::SUCCESS;
}
}
```
To run this example:
1. Create a `composer.json` file in your project root:
```json
{
"require": {
"symfony/console": "^6.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
```
2. Run `composer install` to install the dependencies.
3. Create the `bin` directory and the `console` file inside it (as shown above).
4. Create the `src/Command` directory and the `GreetCommand.php` file inside it (as shown above).
5. Execute from your terminal:
* `php bin/console list` (to see registered commands)
* `php bin/console app:greet` (outputs: "Hello, World!")
* `php bin/console app:greet John` (outputs: "Hello, John!")
* `php bin/console app:greet Jane --yell` (outputs: "YELLING MODE ACTIVATED! HELLO, JANE!")
* `php bin/console app:greet -y Bob` (outputs: "YELLING MODE ACTIVATED! HELLO, BOB!")








symfony/console