Skip to content

Commit 16f21b4

Browse files
[Console] Add signal event
1 parent 8f83b9e commit 16f21b4

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

components/console/events.rst

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,3 +155,20 @@ Listeners receive a
155155
The exit code received in this case is the exception code.
156156

157157
.. _`reserved exit codes`: https://www.tldp.org/LDP/abs/html/exitcodes.html
158+
159+
The ``ConsoleEvents::SIGNAL`` Event
160+
-----------------------------------
161+
162+
**Typical Purposes**: To handle some signals for all application commands.
163+
164+
Listeners receive a
165+
:class:`Symfony\\Component\\Console\\Event\\ConsoleSignalEvent` event::
166+
167+
use Symfony\Component\Console\ConsoleEvents;
168+
use Symfony\Component\Console\Event\ConsoleSignalEvent;
169+
170+
$dispatcher->addListener(ConsoleEvents::SIGNAL, function (ConsoleSignalEvent $event) {
171+
$signal = $event->getHandlingSignal();
172+
173+
// ...
174+
});

console.rst

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,50 @@ call ``setAutoExit(false)`` on it to get the command result in ``CommandTester``
427427
:class:`Symfony\\Component\\Console\\Application <Symfony\\Component\\Console\\Application>`
428428
and extend the normal ``\PHPUnit\Framework\TestCase``.
429429

430+
Command Reacting to Signal
431+
--------------------------
432+
433+
.. versionadded:: 5.2
434+
435+
The :class:`Symfony\Component\Console\Command\SignalableCommandInterface` interface
436+
for reacting to signals was introduced in Symfony 5.2.
437+
438+
You can make your commands react to signals by implementing the `SignalableCommandInterface` interface::
439+
440+
// ...
441+
442+
use Symfony\Component\Console\Command\Command;
443+
use Symfony\Component\Console\Command\SignalableCommandInterface;
444+
445+
class MyCommand extends Command implements SignalableCommandInterface
446+
{
447+
// ...
448+
449+
public function getSubscribedSignals(): array
450+
{
451+
// constants defined by PCNTL extension
452+
// https://www.php.net/manual/en/pcntl.constants.php
453+
return [SIGINT, SIGTERM];
454+
}
455+
456+
public function handleSignal(int $signal): void
457+
{
458+
if (SIGINT === $signal) {
459+
// handle SIGINT signal
460+
}
461+
462+
// ...
463+
}
464+
465+
protected function execute(InputInterface $input, OutputInterface $output): int
466+
{
467+
// ...
468+
// your normal command execution flow
469+
470+
return Command::SUCCESS;
471+
}
472+
}
473+
430474
Logging Command Errors
431475
----------------------
432476

0 commit comments

Comments
 (0)