Command Line
The Symfony framework uses bin/console scripts (such as the well-known bin/console cache:clearcommand) provides a large number of commands. These commands are created through the #Console component. You can also use it to create your own commands.
Create a command ¶
##NamingDefined by classes, these classes must be stored in your bundle (such as AppBundle\Command) Command namespace. The class name must be Command suffixed.
For example, a command named CreateUser must follow this structure:
// src/AppBundle/Command/CreateUserCommand.phpnamespace AppBundle\Command; use Symfony\Component\Console\Command\Command;use Symfony\Component\Console\Input\InputInterface;use Symfony\Component\Console\Output\OutputInterface; class CreateUserCommand extends Command{
protected function configure()
{
// ...
} protected function execute(InputInterface $input, OutputInterface $output)
{
// ...
}}Configuration command ##¶
configure() method. Then optionally define a help message (help message) and Input options and input parameters (Input options and parameters): // ...protected function configure(){
$this
// the name of the command (the part after "bin/console")
// 命令的名字("bin/console" 后面的部分)
->setName('app:create-users') // the short description shown while running "php bin/console list"
// 运行 "php bin/console list" 时的简短描述
->setDescription('Creates new users.') // the full command description shown when running the command with
// the "--help" option
// 运行命令时使用 "--help" 选项时的完整命令描述
->setHelp("This command allows you to create users...")
;}
$ php bin/console app:create-users
execute() method. This method has access to the input stream (such as options and parameters) and the output stream to write information. to the command line): // ...protected function execute(InputInterface $input, OutputInterface $output){
// outputs multiple lines to the console (adding "\n" at the end of each line)
// 输出多行到控制台(在每一行的末尾添加 "\n")
$output->writeln([
'User Creator',
'============',
'',
]); // outputs a message followed by a "\n"
$output->writeln('Whoa!'); // outputs a message without adding a "\n" at the end of the line
$output->write('You are about to ');
$output->write('create a user.');}
## Use input options or parameters to pass information to the command: $ php bin/console app:create-user
User Creator============
Whoa!You are about to create a user.
Console input ¶
use Symfony\Component\Console\Input\InputArgument; // ...protected function configure(){
$this
// configure an argument / 配置一个参数
->addArgument('username', InputArgument::REQUIRED, 'The username of the user.')
// ...
;} // ...public function execute(InputInterface $input, OutputInterface $output){
$output->writeln([
'User Creator',
'============',
'',
]); // retrieve the argument value using getArgument()
// 使用 getArgument() 取出参数值
$output->writeln('Username: '.$input->getArgument('username'));
Now, you can pass the username to the command:
$ php bin/console app:create-user Wouter User Creator============ Username: Wouter
ReferenceConsole output (parameters and options)To learn more about command line options and parameters.
Obtain services from the service container ¶
To actually create a user , the command must access certain services (services). This can be achieved by having the command inherit from ContainerAwareCommand:
// ...use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; class CreateUserCommand extends ContainerAwareCommand{
// ... protected function execute(InputInterface $input, OutputInterface $output)
{
// ... // access the container using getContainer()
// 使用 getContainer() 访问服务容器
$userManager = $this->getContainer()->get('app.user_manager');
$userManager->create($input->getArgument('username')); $output->writeln('User successfully generated!');
}}Now, once You create the required service and its logic, the command will execute app.user_managercreate()# of the service ## method, and then the user will be created Command life cycle
The command has three life cycle methods that can be used when running the command:
- initialize()
(optional) - This method is used in interact()
and execute()Execute before method. Its main purpose is to initialize variables used in the rest of the command's methods. - interact()
(optional) This The method is executed after - initialize()
and beforeexecute(). What it does is check if some options/parameters are missing and then interactively request those values from the user. This is the last place you can ask about missing options/parameters. Thereafter, missing options/arguments will result in an error. - execute()
(required) This method is used between - interact()
andinitialize()Executed later. It contains the logic you want the command to execute.
CommandTester class. It uses special input and output classes to make testing "not in a real console" easy:
// tests/AppBundle/Command/CreateUserCommandTest.phpnamespace Tests\AppBundle\Command; use AppBundle\Command\CreateUserCommand;use Symfony\Bundle\FrameworkBundle\Console\Application;use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;use Symfony\Component\Console\Tester\CommandTester; class CreateUserCommandTest extends KernelTestCase{
public function testExecute()
{
self::bootKernel();
$application = new Application(self::$kernel); $application->add(new CreateUserCommand()); $command = $application->find('app:create-user');
$commandTester = new CommandTester($command);
$commandTester->execute(array(
'command' => $command->getName(), // pass arguments to the helper / 传入参数给helper
'username' => 'Wouter', // prefix the key with a double slash when passing options,
// e.g: '--some-option' => 'option_value',
// 需要选项时,对key加“双中杠”的前缀,如'--some-option' => 'option_value'
)); // the output of the command in the console
// 控制台中的命令输出
$output = $commandTester->getDisplay();
$this->assertContains('Username: Wouter', $output); // ...
}}ApplicationTester you It is also possible to test the entire console program.
Symfony\Component\Console\Application and the regular \PHPUnit_Framework_TestCase.
To use the most complete service container setup in your console tests, you can inherit your tests from KernelTestCase:
// ...use Symfony\Component\Console\Tester\CommandTester;use Symfony\Bundle\FrameworkBundle\Console\Application;use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; class CreateUserCommandTest extends KernelTestCase{
public function testExecute()
{
$kernel = $this->createKernel();
$kernel->boot(); $application = new Application($kernel);
$application->add(new CreateUserCommand()); $command = $application->find('app:create-user');
$commandTester = new CommandTester($command);
$commandTester->execute(array(
'command' => $command->getName(),
'username' => 'Wouter',
)); $output = $commandTester->getDisplay();
$this->assertContains('Username: Wouter', $output); // ...
}}Console Assistant
The Console component also includes a set of "helpers" - different gadgets to help you complete different tasks:
- Question Helper: interactively ask the user for information
- Formatter Helper: customize the output colorization
- Progress Bar: shows a progress bar
- Table: displays tabular data as a table









