【问题标题】:Run multiple Symfony console commands, from within a command在一个命令中运行多个 Symfony 控制台命令
【发布时间】:2016-12-25 08:04:25
【问题描述】:

我在 Symfony 控制台应用程序中定义了两个命令,clean-redis-keysclean-temp-files。我想定义一个命令clean 来执行这两个命令。

我应该怎么做?

【问题讨论】:

    标签: php symfony-components symfony-console


    【解决方案1】:

    请参阅How to Call Other Commands 上的文档:

    从另一个调用命令很简单:

    use Symfony\Component\Console\Input\ArrayInput;
    // ...
    
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $command = $this->getApplication()->find('demo:greet');
    
        $arguments = array(
            'command' => 'demo:greet',
            'name'    => 'Fabien',
            '--yell'  => true,
        );
    
        $greetInput = new ArrayInput($arguments);
        $returnCode = $command->run($greetInput, $output);
    
        // ...
    }
    

    首先,您find() 通过传递命令名称来执行要执行的命令。然后,您需要创建一个新的ArrayInput,其中包含要传递给命令的参数和选项。

    最终,调用run() 方法实际上执行了命令并从命令返回返回的代码(从命令的execute() 方法返回值)。

    【讨论】:

    • 我阅读了文档,它没有显示如何处理 $greetInput 或运行的去向或工作原理
    【解决方案2】:

    获取应用实例,找到命令并执行:

    protected function configure()
    {
        $this->setName('clean');
    }
    
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $app = $this->getApplication();
    
        $cleanRedisKeysCmd = $app->find('clean-redis-keys');
        $cleanRedisKeysInput = new ArrayInput([]);
    
        $cleanTempFilesCmd = $app->find('clean-temp-files');
        $cleanTempFilesInput = new ArrayInput([]);
    
        // Note if "subcommand" returns an exit code, run() method will return it.
        $cleanRedisKeysCmd->run($cleanRedisKeysInput, $output);
        $cleanTempFilesCmd->run($cleanTempFilesInput, $output);
    }
    

    为避免代码重复,您可以创建通用方法来调用子命令。像这样的:

    private function executeSubCommand(string $name, array $parameters, OutputInterface $output)
    {
        return $this->getApplication()
            ->find($name)
            ->run(new ArrayInput($parameters), $output);
    }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      相关资源
      最近更新 更多