Most plugin types have a corresponding alter hook that allows modules to alter or remove plugin definitions.
This is done on cache rebuild, and is system-wide.
In order for more granular and UI-specific filtering, there must also be an alter hook invoked at runtime.
Plugin systems can declare the type of plugin and provide a string identifying themselves.
For example, the Block UI had code to retrieve block plugin definitions that satisfied a set of contexts:
$definitions = $this->blockManager->getDefinitionsForContexts($this->contextRepository->getAvailableContexts());
If the plugin manager implements FilteredPluginManagerInterface, the new getFilteredDefinitions() method may be used:
$definitions = $this->blockManager->getFilteredDefinitions('block_ui', $this->blockManager, $this->contextRepository->getAvailableContexts(), [
'theme' => $theme,
'region' => $region,
]);
The first parameter is the consumer of the plugin definition:
hook_plugin_filter_TYPE_alter($definitions, $extra, $consumer)
hook_plugin_filter_TYPE__CONSUMER_alter($definitions, $extra)
The second parameter is an array of contexts, if available. If you do not wish to filter by contexts, pass NULL.
The third parameter is an associative array of any extra information that could be helpful to the hook implementation. In the case of the Block UI, the theme and region are passed along.
Note that this hook is invoked for both themes and modules.
In order for these hooks to be invoked, the plugin manager must implement \Drupal\Core\Plugin\FilteredPluginManagerInterface
A trait (\Drupal\Core\Plugin\FilteredPluginManagerTrait) is provided to help plugin type authors.
See \Drupal\Core\Block\BlockManager as an example.