New in Symfony 2.3: Events in the Console Component
![Avatar of Fabien Potencier](https://connect.symfony.com/api/images/4aed4f5d-e0cb-4320-902f-885fddaa7d15.png?format=28x28)
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Fabien Potencier
in #7466.
Today, I'm about to write about one of the oldest feature requests for the Console component: the possibility to hook during the lifecycle of a command execution. I have been delaying this feature for a long time as I did not want to introduce a hard dependency between the Console component and the Event Dispatcher component.
But as of Symfony 2.3, you can listen to several events that are dispatched by the main console application:
1 2 3 4 5 6 7 8
use Symfony\Component\Console\Application;
use Symfony\Component\EventDispatcher\EventDispatcher;
$dispatcher = new EventDispatcher();
$application = new Application();
$application->setDispatcher($dispatcher);
$application->run();
Note that events are only dispatched if you inject an event dispatcher.
Three events are automatically dispatched:
ConsoleEvents::COMMAND
lets you do something before a command is executed;ConsoleEvents::TERMINATE
lets you perform some cleanup actions after the command has been executed;ConsoleEvents::EXCEPTION
lets you handle exceptions thrown during the execution of a command.
If you want to see some code example, read the full documentation about this new feature in the Console component documentation.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments
![Avatar of Oleg Andreyev](https://connect.symfony.com/api/images/6bf3bd7d-54cf-406c-be1e-2ae20e19c062.png?format=48x48)
![Avatar of Kevin Bond](https://connect.symfony.com/api/images/e5418fe1-bff7-4bce-a883-c736ea30ca11.png?format=48x48)
![Avatar of Christophe Coevoet](https://connect.symfony.com/api/images/c81121f4-fd7a-49b0-9284-cef4b0dde8e7.png?format=48x48)
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.