Working in Public: The Making and Maintenance of Open Source Software Audible Audiobook
Free with Audible trial
Derivers in Drupal are one of the ways in which you can inform Drupal about the presence of plugin types. This allows you to generate multiple custom types of a plugin so that it can be represented as multiple different plugins within the system.
Perhaps the most useful deriver example I have seen is the menu deriver. This allows us to use the Drupal plugin architecture to generate custom menu links.
If you want to create a menu link for your module then you would normally add them one at a time to a *.links.menu.yml file. This is an example of using the menu links plugin system to inform the menu system about the links you want to add.
For example, the core config module has a single option in the config.links.menu.yml file that adds the “Configuration synchronization” menu item to the administration menu. Here is the contents of that file.
config.sync: title: 'Configuration synchronization' description: 'Import and export your configuration.' route_name: config.sync parent: system.admin_config_development
Instead of doing this, we can use a menu deriver to tell the menu system to look at a class that will then inject menu links into the menu. This saves us from adding them one by one and also means we can dynamically create menu links without hard coding them into the *.links.menu.yml file.
In this article, I will look at setting up a menu deriver and then using that deriver to inject custom elements into the menu.
Setting Up A Menu Deriver
The first thing to do is setup a menu deriver class. This should implement a method called getDerivativeDefinitions() which will return the plugin derivatives. As we are calling this from the menu system we need to return an array of menu links from this method so that they are understood by the menu system.