PHP code example of webmozarts / console-parallelization
1. Go to this page and download the library: Download webmozarts/console-parallelization library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
webmozarts / console-parallelization example snippets
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Webmozarts\Console\Parallelization\ParallelCommand;
use Webmozarts\Console\Parallelization\Parallelization;
use Webmozarts\Console\Parallelization\Input\ParallelizationInput;
class ImportMoviesCommand extends ParallelCommand
{
public function __construct()
{
parent::__construct('import:movies');
}
protected function configure(): void
{
parent::configure();
// ...
}
protected function fetchItems(InputInterface $input, OutputInterface $output): iterable
{
// open up the file and read movie data...
// return items as strings
return [
'{"id": 1, "name": "Star Wars"}',
'{"id": 2, "name": "Django Unchained"}',
// ...
];
}
protected function runSingleCommand(string $item, InputInterface $input, OutputInterface $output): void
{
$movieData = json_decode($item);
// insert into the database
}
protected function getItemName(?int $count): string
{
if (null === $count) {
return 'movie(s)';
}
return 1 === $count ? 'movie' : 'movies';
}
}
// When using the ParallelCommand
protected function runBeforeBatch(InputInterface $input, OutputInterface $output, array $items): void
{
// e.g. fetch needed resources collectively
}
protected function runAfterBatch(InputInterface $input, OutputInterface $output, array $items): void
{
// e.g. flush database changes and free resources
}
protected function configureParallelExecutableFactory(
ParallelExecutorFactory $parallelExecutorFactory,
InputInterface $input,
OutputInterface $output,
): ParallelExecutorFactory {
return $parallelExecutorFactory
->withRunAfterBatch($this->runBeforeBatch(...))
->withRunAfterBatch($this->runAfterBatch(...));
}
// When using the Parallelization trait, this can be simplified a bit:
protected function runBeforeBatch(
InputInterface $input,
OutputInterface $output,
array $items
): void {
// ...
}