명령줄


bin/consolebin/console脚本(如,广为人知的bin/console cache:clear命令)提供了大量命令。这些命令是通过控制台组件被创建的。你也可以使用它创建自己的命令。

创建一个命令 

命名通过类来定义,这些类必须存放在你的束(如AppBundleCommand)的Command命名空间下。类名必须是Command后缀。

例如,一个名为CreateUser的命令必须遵循此结构:

// 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)
    {
        // ...
    }}

配置命令 

首先,你必须在configure()方法中配置命令的名称。然后可选地定义一个帮助信息(帮助消息)和输入选项及输入参数(输入选项和参数):

// ...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()을 통한 Symfony 프레임워크 스크립트(예: 잘 알려진 bin/console 캐시:clear

명령)는 많은 수의 명령을 제공합니다. . 이러한 명령은

콘솔 구성 요소

#🎜🎜##🎜🎜#을 통해 생성됩니다. 이를 사용하여 자신만의 명령을 만들 수도 있습니다. #🎜🎜##🎜🎜##🎜🎜#

#🎜🎜##🎜🎜#명령 만들기 #

code class="notranslate">AppBundleCommand#🎜🎜##🎜🎜 #) of #🎜🎜##🎜🎜#Command#🎜🎜##🎜🎜 #네임스페이스 아래. 클래스 이름에는 #🎜🎜##🎜🎜#Command#🎜🎜##🎜🎜# 접미사가 붙어야 합니다. #🎜🎜##🎜🎜##🎜🎜##🎜🎜##🎜🎜##🎜🎜#예를 들어, #🎜🎜##🎜🎜#CreateUser #🎜🎜##🎜🎜#에 대한 명령은 다음 구조를 따라야 합니다. #🎜🎜##🎜🎜##🎜🎜#
// ...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.');}
#🎜🎜##🎜🎜##🎜🎜#구성 명령 #🎜🎜##🎜 🎜# #🎜🎜##🎜🎜#¶#🎜🎜##🎜🎜#
#🎜🎜# #🎜 🎜##🎜🎜##🎜🎜#먼저 #🎜🎜##🎜🎜#configure()#🎜🎜##🎜에서 명령을 구성해야 합니다. 🎜# 메소드 이름. 그런 다음 선택적으로 도움말 메시지(도움말 메시지)를 정의하고 #🎜🎜##🎜🎜##🎜🎜##🎜🎜# 입력 옵션을 정의합니다. 및 입력 매개변수 #🎜🎜##🎜🎜##🎜🎜##🎜🎜#(입력 옵션 및 매개변수): #🎜🎜##🎜🎜##🎜🎜#
$  php bin/console app:create-user
User Creator============ 
Whoa!You are about to create a user.
# 🎜🎜 ##🎜🎜##🎜🎜#명령 실행 #🎜🎜##🎜🎜##🎜🎜##🎜🎜#¶# 🎜🎜 ##🎜🎜#
#🎜🎜##🎜🎜##🎜🎜##🎜🎜#명령어를 구성한 후 터미널(터미널)에서 실행할 수 있습니다. #🎜🎜 ## 🎜🎜##🎜🎜#
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'));
#🎜🎜##🎜🎜##🎜🎜# 아직 로직을 작성하지 않았으므로 이 명령은 아무 작업도 수행하지 않을 것으로 예상할 수 있습니다. 입력 스트림(예: 옵션 및 매개변수) 및 출력에 액세스할 수 있는 #🎜🎜##🎜🎜#execute()#🎜🎜##🎜🎜# 메서드에 자신만의 논리를 추가하세요. stream은 명령줄에 정보를 씁니다.): #🎜🎜##🎜🎜##🎜🎜#
$  php bin/console app:create-user Wouter
User Creator============ 
Username: Wouter
#🎜🎜##🎜🎜##🎜🎜#이제 다음 명령을 실행해 보세요. #🎜🎜##🎜🎜# # 🎜🎜#
// ...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!');
    }}

콘솔 입력 # 🎜 🎜#

입력 옵션 또는 매개변수를 사용하여 명령에 정보를 전달합니다.

// 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);         // ...
    }}

#🎜 🎜 #이제 사용자 이름을 명령에 전달할 수 있습니다:

// ...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);         // ...
    }}

#🎜🎜 #참조

콘솔 출력(매개변수 및 옵션)에서 명령줄 옵션과 매개변수 정보에 대해 자세히 알아보세요.

서비스 컨테이너에서 서비스 가져오기

실제로 사용자를 생성하려면 명령이 일부 services에 액세스해야 합니다. 이는 명령이 ContainerAwareCommandContainerAwareCommand来实现:

rrreee

现在,一旦你创建了所需的服务及其逻辑,命令将执行app.user_manager服务的create()方法,然后用户会被创建的命令生命周期  

命令有三个生命周期方法可以在运行命令时使用:

  • initialize() (可选)
  • 这个方法在interact()execute()方法之前执行。它的主要作用是初始化那些用在命令其余方法中的变量。
  • interact() (可选)
  • 此方法在 initialize() 之后、 execute() 之前执行。它的作用是检查是否错失了某些选项/参数,然后以互动方式向用户请求这些值。这是你可以问询错失的选项/参数的最后一个地方。此后,丢失的选项/参数将导致一个错误。
  • execute() (必须)
  • 此方法在 interact() and initialize() 之后执行。它包含你希望命令去执行的逻辑。

测试命令 ¶

Symfony提供了几个工具来帮你测试命令。最有用的一个是 CommandTester 类。它使用特殊的input和output类,令“不在真正控制台中”的测试变得容易:

rrreee


使用 ApplicationTester 你也可以测试整个控制台程序。


当Console组件被单独使用时,使用 SymfonyComponentConsoleApplication 和常规的 PHPUnit_Framework_TestCase

에서 상속받도록 하여 달성할 수 있습니다.
🎜rrreee🎜🎜🎜 이제 필요한 서비스와 해당 논리를 생성한 후에는 명령이 다음과 같이 실행됩니다. 🎜🎜app.user_manager🎜🎜 서비스의 🎜🎜create()🎜🎜 메소드를 실행하면 사용자가 생성됩니다 🎜🎜 명령 수명 주기 🎜🎜🎜🎜명령에는 명령을 실행할 때 사용할 수 있는 세 가지 수명 주기 방법이 있습니다: 🎜🎜🎜
  • initialize() 🎜 🎜🎜 (선택 사항) 🎜🎜🎜
  • 🎜🎜이 메서드는 🎜🎜interact()🎜🎜 및 🎜🎜execute()는 🎜🎜 메서드 이전에 실행됩니다. 주요 목적은 명령의 나머지 메소드에 사용되는 변수를 초기화하는 것입니다. 🎜🎜
  • interact() 🎜🎜🎜(선택 사항)🎜🎜🎜
  • 이 메서드는 initialize() 이후 및 execute() 이전에 실행됩니다. 이것이 하는 일은 일부 옵션/매개변수가 누락되었는지 확인한 다음 대화형으로 사용자에게 해당 값을 요청하는 것입니다. 누락된 옵션/매개변수에 대해 문의할 수 있는 마지막 장소입니다. 그 이후에는 옵션/인수가 누락되면 오류가 발생합니다.
  • execute() 🎜(필수)🎜
  • 이 메서드는 interact()<에 있습니다. / code> 및 initialize()가 이후에 실행됩니다. 여기에는 명령을 실행하려는 논리가 포함되어 있습니다.
🎜명령 테스트 ¶🎜🎜Symfony는 명령 테스트에 도움이 되는 여러 도구를 제공합니다. 가장 유용한 것은 CommandTester 클래스입니다. 특별한 입력 및 출력 클래스를 사용하여 "실제 콘솔이 아닌" 테스트를 쉽게 만듭니다. 🎜rrreee🎜
🎜

ApplicationTester 전체 콘솔 애플리케이션을 테스트할 수도 있습니다. 🎜🎜🎜
🎜

콘솔 구성요소를 단독으로 사용하는 경우 다음을 사용하세요. SymfonyComponentConsoleApplication 및 일반 PHPUnit_Framework_TestCase. 🎜🎜🎜

콘솔 테스트에서 가장 완벽한 서비스 컨테이너 설정을 사용하려면 KernelTestCase에서 테스트를 상속할 수 있습니다.

rrreee

콘솔 도우미

콘솔 구성 요소에는 "도우미" 세트도 포함되어 있습니다. 다양한 가젯을 사용하면 다양한 작업을 완료할 수 있습니다.

  • 질문 도우미 : 대화형으로 사용자에게 정보 요청
  • Formatter 도우미 : 출력 색상 사용자 정의
  • 진행률 표시줄(진행률 표시줄): 진행률 표시줄 표시
  • 테이블(테이블): 표시 테이블 형식 데이터