From Plugin API Overview:
Plugins are small pieces of functionality that are swappable. Plugins that perform similar functionality are of the same plugin type.
Drupal contains many different plugins, of different types. For example, 'Field widget' is a plugin type, and each different field widget type is a plugin. The admin user may select from the list of field widget plugins to set the widget that a field uses.
The D8 plugin system provides a set of guidelines and reusable code components to allow developers to expose pluggable components within their code and (as needed) support managing these components through the user interface.
Plugins are defined by modules: a module may provide plugins of different types, and different modules may provide their own plugins of a particular type.
- Plugin Types are the controlling class defining discovery and instantiation of plugins of that type.
A plugin type should be have a meaningful name as to describe the purpose of plugins of that type (e.g. Cache Backend, or Block)
-
Plugin Discovery is the process of finding plugins in the code base.
Plugin discovery types, from Drupal 8 Plugin Discovery:
-
StaticDiscovery
allows for direct registration of plugins within the discovery class itself. A protected variable ($definitions
) in the class holds all plugin definitions that are registered with it through the public methodsetDefinition()
. Any plugin defined through this method can then be invoked as outlined in the plugin manager documentation. -
HookDiscovery
allows Drupal'shook_component_info()
/hook_component_info_alter()
pattern to be used for plugin discovery. With this discovery, the plugin manager will invoke info hooks to retrieve a list of available plugins. -
AnnotatedClassDiscovery
uses name of the annotations that contains the plugin definition, e.g.,@Plugin
,@EntityType
, in plugin docblocks to discover plugins, minimizing memory usage during the discovery phase. TheAnnotatedClassDiscovery
class takes an argument in its constructor,$subdir
, which specifies the sub-directory/sub-namespace for this plugin type. TheAnnotatedClassDiscovery
class scans PSR-4 classes inside those sub-directories of Plugin folders to find plugins (see a "Annotations-based plugins"). -
YamlDiscovery
allows plugins to be defined in yaml files. Drupal core uses this for local tasks and local actions.
-
-
Plugin Factory instantiates specific plugins.
Assume you are adding a Constraint
plugin (see detailed example here)
Register your plugin by placing it in a file relative to your module root, (e.g. src/Plugin/Constraint/UserNameUnique.php
).
<?php
/**
* @Constraint(
* id = "UserNameUnique",
* label = @Translation("User name unique", context = "Validation"),
* )
*/
class UserNameUnique extends Constraint {
// ...
}
?>
Important Note: Unlike other PHP coding standards, annotations should always use double quotes instead of single quotes.