Per entity type events for entity hooks

Created on 20 October 2022, almost 2 years ago
Updated 17 June 2024, 3 months ago

Problem/Motivation

Drupal Core provides per entity type hooks for entity operations via hook_ENTITY_TYPE_presave(), hook_ENTITY_TYPE_load(), etc.

So we can use hook_node_presave() to act only on Nodes, hook_user_presave() - on Users, etc.

But Hook Event Dispatcher seems provides only a global events for all entitles, like EntityHookEvents::ENTITY_PRE_SAVE?

I know, that I can add something like this to disable acting a global Event Subscriber on unneeded entity types:

  public function myUserPreSaveSubscriber(EntityPresaveEvent $event): void {
    if (!$event->getEntity() instanceof \Drupal\user\Entity\User) {
      return;
    }
    ...
  }

But this trick will not disable the calling of the subscriber, so will little slow down save operations for all entity types, because on each entity save event it will call this function and make the comparison.

Proposed resolution

Will be good to register also individual events for each available entity type. Is it possible? How hard to implement this?

If this already possible, please add some examples how to use it.

Remaining tasks

User interface changes

API changes

Data model changes

✨ Feature request
Status

RTBC

Version

3.3

Component

Code

Created by

πŸ‡¦πŸ‡²Armenia murz Yerevan, Armenia

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ͺπŸ‡ΈSpain JoseFran

    I am interested in prove this funcionality. How can i apply a patch? I'm sorry for the inconvenience.

  • Status changed to RTBC 12 months ago
  • πŸ‡¦πŸ‡²Armenia murz Yerevan, Armenia

    I rebased the MR on the fresh HEAD, and reviewed the changes. For me, all look good and work well for my cases. So moving to Reviewed status to move forward.

    @JoseFran, to apply a patch you can get the patch code by the "plain diff" link in the MR block.

  • πŸ‡ΊπŸ‡ΈUnited States maskedjellybean Portland, OR
  • πŸ‡ΊπŸ‡ΈUnited States maskedjellybean Portland, OR

    Hey @JoseFran, you can generate a patch at: https://git.drupalcode.org/project/hook_event_dispatcher/-/merge_request... (just add .patch to the merge request URL).

    @murz, can you explain how to use this feature once the patch is applied? I'd like to implement hook_ENTITY_TYPE_view.

    I added a related issue that was seemingly incorrectly closed. Just to reiterate what was pointed out in that issue, there is almost certainly a performance penalty for using hook_entity_view when really you only need hook_ENTITY_TYPE_view. The first is called when viewing any entity and the second is only called when viewing a specific entity type. If events are going to be as performant as hooks then this needs to be figured out.

Production build 0.71.5 2024