Symfony进度条在命令调用服务

rfc*_*484 5 php console command symfony progress-bar

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

use Symfony\Component\Console\Helper\ProgressBar;

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

$progress->start();

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

$progress->finish()
Run Code Online (Sandbox Code Playgroud)

但是,如果您只在命令中调用服务,该怎么办:

// 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) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

无论如何以与命令文件中类似的方式输出服务foreach循环中的进度?

jcr*_*oll 7

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

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);
}
Run Code Online (Sandbox Code Playgroud)