symandy/progress-event

用于处理控制台进度条的 Symfony 服务中使用的事件

v0.1.0 2022-02-11 16:21 UTC

This package is auto-updated.

Last update: 2024-08-29 06:01:52 UTC


README

此包包含一组事件和订阅者,可在 Symfony 服务中使用。

目的是将 Symfony 进度条处理外部化,并使用进度条事件。

安装

composer require symandy/progress-event

使用

  1. 在您的 Symfony 命令中,在调用执行任务的服务的服务之前,注册一个可用的订阅者。
<?php

use Symandy\Component\ProgressEvent\EventSubscriber\ProgressBarSubscriber;
use Symandy\Component\ProgressEvent\EventSubscriber\SymfonyStyleSubscriber;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

final class FooCommand extends Command
{
    private EventDispatcherInterface $eventDispatcher;

    private FooHandler $fooHandler;
 
    // Configure command 

    protected function execute(InputInterface $input, OutputInterface $output): int
    {    
        // Use the basic progress bar
        $this->eventDispatcher->addSubscriber(new ProgressBarSubscriber(new ProgressBar($output)));
     
        // Or use the Symfony style progress bar
        $io = new SymfonyStyle($input, $output);
        $this->eventDispatcher->addSubscriber(new SymfonyStyleSubscriber($io));

        $this->fooHandler->handleComplexTask();

        return Command::SUCCESS;
    }
}
  1. 在处理一些复杂任务时派发所需的事件
<?php

use Symandy\Component\ProgressEvent\Event\AdvanceEvent;
use Symandy\Component\ProgressEvent\Event\FinishEvent;
use Symandy\Component\ProgressEvent\Event\StartEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

final class FooHandler
{
    private EventDispatcherInterface $eventDispatcher;

    public function __construct(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    public function handleComplexTask(): void
    {
        $items = ['foo', 'bar', 'baz'];

        $this->eventDispatcher->dispatch(new StartEvent(count($items)));

        foreach ($items as $item) {
            // Handle some complex task

            $this->eventDispatcher->dispatch(new AdvanceEvent());
        }

        $this->eventDispatcher->dispatch(new FinishEvent());
    }
}