2

Do you think it would be a good practice to replace hooks with events? I mean dispatching an event inside a hook to subscribe afterwards.

For example if you have 20 hooks in your module, is it recommended to dispatch an event for each hook, or just keep using the hooks as usual?

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function my_module_node_insert(EntityInterface $entity) {
  // Dispatch the node insert event so that subscribers can act accordingly.
  \Drupal::service('event_dispatcher')->dispatch(NodeInsertEvent::NODE_INSERT, new NodeInsertEvent($entity));
}
2
  • 5
    This doesn't replace the hook and I see no benefits as long as you are the only one subscribing to the custom event while other modules still use the core hook. Replacing the hook would be a decision to be made by the core maintainers.
    – 4uk4
    Feb 21, 2019 at 20:48
  • 4
    For example if you have 20 hooks in your .module file? then you simply have 20 specific needs to subscribe to those hooks. You can't just route them all into a singular event, you'd probably wind up with multiple events subscribers which now turns 1 file into multiple (per module, potentially) and doesn't change the scenario very much. Like 4k4 said, this doesn't really benefit anyone until core maintainers implement such a thing in the future. The code you write here wouldn't be very portable without hauling the custom events everywhere you go.
    – Kevin
    Feb 21, 2019 at 21:37

1 Answer 1

2

Perhaps. I know other developers are using Hook Event Dispatcher because they want to guard against if the hook system goes away in D9. Thus, saving time in the future if indeed they go away.

Whether they go away its pure speculation at this point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.