df8a363833c3f8aa5fa7893239a15a268b7f1d7a
[yaffs-website] / vendor / drush / drush / docs / hooks.md
1 Core Hooks
2 ============
3 All commandfiles may implement methods that are called by Drush at various times in the request cycle. To implement one, add a `@hook validate` (for example) to the top of your method.
4
5 - [Documentation about available hooks](https://github.com/consolidation/annotated-command#hooks).
6 - To see how core commands implement a hook, you can [search the Drush source code](https://github.com/drush-ops/drush/search?q=%40hook+validate&type=Code&utf8=%E2%9C%93). This link uses validate hook as an example.
7
8 Custom Hooks
9 ============
10
11 Drush commands can define custom events that other command files can hook. You can find examples in [CacheCommands](https://github.com/drush-ops/drush/blob/master/src/Commands/core/CacheCommands.php) and [SanitizeCommands](https://github.com/drush-ops/drush/blob/master/src/Drupal/Commands/sql/SanitizeCommands.php)
12
13 First, the command must implement CustomEventAwareInterface and use CustomEventAwareTrait, as described in the [dependency injection](dependency-injection.md) documentation.
14
15 Then, the command may ask the provided hook manager to return a list of handlers with a certain annotation. In the example below, the `my-event` label is used:
16 ```
17     /**
18      * This command uses a custom event 'my-event' to collect data.  Note that
19      * the event handlers will not be found unless the hook manager is
20      * injected into this command handler object via `setHookManager()`
21      * (defined in CustomEventAwareTrait).
22      *
23      * @command example:command
24      */
25     public function exampleCommand()
26     {
27         $myEventHandlers = $this->getCustomEventHandlers('my-event');
28         $result = [];
29         foreach ($myEventHandlers as $handler) {
30             $result[] = $handler();
31         }
32         sort($result);
33         return implode(',', $result);
34     }
35 ```
36
37 Other command handlers may provide implementations by implementing `@hook on-event my-event`.
38
39 ```
40     /**
41      * @hook on-event my-event
42      */
43     public function hookOne()
44     {
45         return 'one';
46     }
47 ```