Problem/Motivation
Drupal prides itself on providing an extensible system, allowing modules to hook into and override many parts of its core functionality. Sometimes we make this more difficult than we need to. As an example, reacting to entity events is currently confusing and difficult. There are a myriad of hooks and events that a module might want to react to, and they are confusing and poorly documented. Responding to events is particularly difficult, you have to create a service, figure out which events you want to respond to and worry about injecting any supporting services that you might need.
What if there was an easier way? "One hook to rule them all"? By implementing this one simple, hook, a module can condense all of it's entity related overrides into a single, consolidated, easy to read method:
hook_entityapi(EntityInterface &$entity, string $op, mixed $a3, mixed $a4)
The beauty is in its simplicity. We pass in the entity and a string describing the operation being performed. Parameters $a3 and $a4 are magic parameters whose values will depend on the operation. $op can be anything, 'save', 'presave', 'load', 'display', 'translate', or anything else we need to do. We can continue to add operations and preserve backwards compatibility.
For example, content moderation might use:
hook_entityapi($entity, 'transition', $previous_moderation_state, $current_moderation_state)
One concern with this proposal might be that this hook may be long and unwieldy, that it might devolve into a giant switch statement, (or nested switch statements to deal with multiple entity types and operations. Fortunately, PHP provides a mechanism to clean up this function. The recommended use of this hook is as follows:
function my_module_entityapi(&$entity, $op, $a3, $a4) {
if ($entity->getEntityTypeId() === 'node' && $op === 'save') {
goto node_save;
}
else if ($entity->getEntityTypeId === 'user' && $op === 'load') {
goto user_load;
}
return;
node_save:
// do stuff
return
user_load:
// do stuff
return
}
Additional benefits to module maintainers:
- Testability: All entity api related code lives in one unit testable method, no need for kernel or functional tests in most cases.
- Dependency Injection: We aren't in a class context, so you don't have to worry about it, just use \Drupal::service()!
Proposed resolution
Deprecate all entity api related hooks and events, and switch to this one hook for entity api related functions. (I'm sure Berdir can whip up a patch for this in a day or two)
Commit it!
Remaining tasks
Do it!
User interface changes
None
API changes
Minor change in entity api system to use a single universal hook.
Data model changes
None needed.
Release notes snippet
Drupal has improved extensibility in the Entity API systems
Comments
Comment #2
mikelutzComment #3
mikelutzComment #4
mikelutzComment #5
mikelutzComment #6
berdir> 1 Apr 2019
Lets close this before someone starts to implement a patch ;) Closing as outdated because it's no longer April 1st ;)