【问题标题】:Symfony progress bar in command calling to service命令调用服务中的 Symfony 进度条
【发布时间】:2016-01-12 17:35:45
【问题描述】:

您可以通过这种方式在命令中显示进度条:

use Symfony\Component\Console\Helper\ProgressBar;

$progress = new ProgressBar($output, 50);

$progress->start();

$i = 0;
while ($i++ < 50) {
    $progress->advance();
}

$progress->finish()

但是如果你只在命令中调用了一个服务呢:

// command file
$this->getContainer()->get('update.product.countries')->update();

// service file
public function update()
{
    $validCountryCodes = $this->countryRepository->findAll();

    $products = $this->productRepository->findWithInvalidCountryCode($validCountryCodes);

    foreach ($products as $product) {
        ...
    }
}

有没有以与命令文件中类似的方式输出服务 foreach 循环中的进度?

【问题讨论】:

    标签: php symfony console command progress-bar


    【解决方案1】:

    您将需要以某种方式修改该方法。这是一个例子:

    public function update(\Closure $callback = null)
    {
        $validCountryCodes = $this->countryRepository->findAll();
    
        $products = $this->productRepository->findWithInvalidCountryCode($validCountryCodes);
    
        foreach ($products as $product) {
            if ($callback) {
                $callback($product);
            }
            ...
        }
    }
    
    /**
     * command file
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $progress = new ProgressBar($output, 50);
    
        $progress->start();
    
        $callback = function ($product) use ($progress) {
            $progress->advance();
        };
        $this->getContainer()->get('update.product.countries')->update($callback);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多