How to best store and retrieve a tree-style in a relational DB? This pattern is more common than we think. Examples would be hierarchical tags and threaded comments or discussions.
Drupal 8 has this concept of services, or reusable PHP objects. The distinguishing feature of services is that their initiation is configurable. In other words, we can configure what type of instance is created and when this instance is created in the code, mostly without changing the code at all.
Why is this a big deal?
Real world plugins have a lot more properties than the
label property mentioned in our breakfast plugin. To make our plugin more "real world", we introduce 2 properties, image and ingredients.
- Implementing a new plugin from existing plugin types.
- Implementing a new plugin type using the annotation based discovery mechanism.
As an exercise, let's first construct an imaginary scenario where the user of your Drupal site wants choose what they want for breakfast from a list of breakfast menu items.
We saw in part 1 how plugins help us in writing reusable functionality in Drupal 8. There are a lot of concepts which plugins share in common with services, like:
- limited scope. Do one thing and do it right.
- PHP classes which are swappable.
Which begs the question, how exactly are plugins different from services? If your interface expects implementations to yield the same behaviour, then go for services. Otherwise, you should write it as a plugin.