Skip to content

Commit 1fc1bca

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

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-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: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,48 @@ 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 Signals
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+
use Symfony\Component\Console\Command\Command;
442+
use Symfony\Component\Console\Command\SignalableCommandInterface;
443+
444+
class CreateUserCommand extends Command implements SignalableCommandInterface
445+
{
446+
// ...
447+
448+
public function getSubscribedSignals(): array
449+
{
450+
// constants defined by PCNTL extension
451+
// https://www.php.net/manual/en/pcntl.constants.php
452+
return [SIGINT, SIGTERM];
453+
}
454+
455+
public function handleSignal(int $signal): void
456+
{
457+
if (SIGINT === $signal) {
458+
// handle SIGINT signal
459+
}
460+
461+
// handle SIGTERM signal
462+
}
463+
464+
protected function execute(InputInterface $input, OutputInterface $output): int
465+
{
466+
// ...
467+
468+
return Command::SUCCESS;
469+
}
470+
}
471+
430472
Logging Command Errors
431473
----------------------
432474

0 commit comments

Comments
 (0)