Skip to content

Events and Event Listeners

Tip

  1. 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: OptionsetSqlListener
  • Symfony\Component\Console\Event\ConsoleCommandEvent. Used to act before a command fires. That is, populate user input, check for validity, etc. Example: ValidateQueueNameListener
  • Symfony\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:

  1. The class namespace, relative to base namespace, should be Drupal\<module-name>\Drush\Listeners and the class file should be located under the src/Drush/Listeners directory.
  2. The filename must have a name like FooListener.php. The prefix Foo can be whatever string you want. The file must end in Listener.php.
  3. The class should implement the #[AsListener] PHP Attribute.
  4. Implement your logic via a __invoke(ConsoleDefinitionsEvent $event) method. Use a different type hint to listen on a different Event.
  5. Inject the logger and any other needed dependencies in the class constructor.

Another example is the WootDefinitionListener provided by the testing 'woot' module.