Drupal 8 OOP benefit 1 of many: entity types
by Alex Bronstein
Many people, including me, have been blogging about Drupal 8 and its transition to object oriented programming. One question that comes up often is why?, given the extra layers of abstraction, complexity, and verbosity that often accompanies that. Dries wrote a post, answering that question at a high level. In this post, I want to quickly highlight one place, entity types, where the abstractions have what I think to be very obvious and impressive benefits. I believe there are many other places as well; I'm just limiting this blog post to the one.
If you follow those links, you'll notice that:
- 3 of those 4 are quite lengthy functions, and even image_style_save() isn't entirely trivial.
- They share some similarities. For example, they all write to the database, deal with default values, and invoke at least one hook.
- There are also some differences. For example, image_style_save() receives an array and passes the array to the hook it invokes, whereas the others receive an object (just a data object, not an OOP-style classed object) and pass the object to the hooks, and user_save() receives (and passes along to the hooks) other information besides the primary object. Also, image_style_save() invokes just a single hook: hook_image_style_save(), while filter_format_save() invokes either hook_filter_format_insert() or hook_filter_format_update(), and node_save() and user_save() invoke presave hooks in addition to the insert and update ones.
Now consider that the function length, pointless differences (which people writing modules that implement those hooks need to keep track of), and duplication of code that's similar, is multiplied to dozens of such thingies in core (and a whole bunch more throughout contrib) and several operations besides save().
In Drupal 8, the official term for these thingies is entity types, and the Entity API provides base classes so that each entity type only needs to write the code for the stuff it does that's special for that type. For example, the node entity type is implemented with the Node class, and its only custom save logic is a 1 line preSave() method and a 3 line postSave() method.
This results in less code to implement each entity type, and it means that the hooks across all operations of all 40 entity types in Drupal 8 core are consistent.
Acquia Insight Subscription