Events and Event Listeners¶
Tip
- As of Drush 13.7.0, Drush recommends using listeners to modify the behavior of other commandfiles. Prior versions used hooks which are now deprecated.
Drush makes use of standard Symfony Console events. In addition, it also fires a custom ConsoleDefinitionsEvent event (see below). Further, commands can inject an event dispatcher service via autowire (use \Psr\EventDispatcher\EventDispatcherInterface as the type hint) and then dispatch their own events (e.g. sql:sanitize, cache:clear).
Drush\Event\ConsoleDefinitionsEvent. Used to modify command definitions. That is, add/remove options, usages, etc. Example: OptionsetSqlListenerSymfony\Component\Console\Event\ConsoleCommandEvent. Used to act before a command fires. That is, populate user input, check for validity, etc. Example: ValidateQueueNameListenerSymfony\Component\Console\Event\ConsoleTerminateEvent. Used to run code after a command completes. Example: DrupliconListener
Implementing a listener¶
In the module that wants to alter command info, add a class that:
- The class namespace, relative to base namespace, should be
Drupal\<module-name>\Drush\Listenersand the class file should be located under thesrc/Drush/Listenersdirectory. - The filename must have a name like FooListener.php. The prefix
Foocan be whatever string you want. The file must end inListener.php. - The class should implement the
#[AsListener]PHP Attribute. - Implement your logic via a
__invoke(ConsoleDefinitionsEvent $event)method. Use a different type hint to listen on a different Event. - Inject the logger and any other needed dependencies in the class constructor.
Another example is the WootDefinitionListener provided by the testing 'woot' module.