Symfony进度条在命令调用服务


Symfony progress bar in command calling to service

在命令中显示进度条的方式如下:

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循环中以类似于命令文件中的方式输出进度?

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

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