Skip to content

Commit d32cf04

Browse files
authored
Added option enable-event-dispatcher to initialize EventDispatcher for command. (#2420)
* Added trait EnableEventDispatcher for command. * Update CHANGELOG-2.0.md
1 parent f20a5cd commit d32cf04

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

src/Command.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727

2828
abstract class Command extends SymfonyCommand
2929
{
30+
use EnableEventDispatcher;
31+
3032
/**
3133
* The name of the command.
3234
*
@@ -421,10 +423,13 @@ protected function configure()
421423
if (! isset($this->signature)) {
422424
$this->specifyParameters();
423425
}
426+
427+
$this->addEnableDispatcherOption();
424428
}
425429

426430
protected function execute(InputInterface $input, OutputInterface $output)
427431
{
432+
$this->enableDispatcher($input);
428433
$callback = function () {
429434
try {
430435
$this->eventDispatcher && $this->eventDispatcher->dispatch(new Event\BeforeHandle($this));

src/EnableEventDispatcher.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
/**
5+
* This file is part of Hyperf.
6+
*
7+
* @link https://www.hyperf.io
8+
* @document https://hyperf.wiki
9+
* @contact group@hyperf.io
10+
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
11+
*/
12+
namespace Hyperf\Command;
13+
14+
use Hyperf\Utils\ApplicationContext;
15+
use Psr\EventDispatcher\EventDispatcherInterface;
16+
use Symfony\Component\Console\Input\InputInterface;
17+
use Symfony\Component\Console\Input\InputOption;
18+
19+
trait EnableEventDispatcher
20+
{
21+
public function addEnableDispatcherOption()
22+
{
23+
$this->addOption('enable-event-dispatcher', null, InputOption::VALUE_NONE, 'Whether enable event dispatcher.');
24+
}
25+
26+
public function enableDispatcher(InputInterface $input)
27+
{
28+
if ($input->getOption('enable-event-dispatcher')) {
29+
$this->eventDispatcher = ApplicationContext::getContainer()->get(EventDispatcherInterface::class);
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)