2015-10-14 64 views
4

您可以用这种方式显示的命令的进度条:Symfony的进度条调用的服务

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循环中的进度?

回答

6

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

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