A Drupal plugin is a set of codes defined according to a concept that solves specific needs.
Plugins are loaded automatically on an as-needed basis, but there may be occasions when you wish to load your plugin manually.
Several approaches are available to load your plugin.
1: createInstance
The createInstance method is used to create an instance of the plugin. To use this method, you need to determine the plugin manager.
For example, name the “boolean” plugin (core/modules/views/src/Plugin/views/filter/BooleanOperator.php).
...
* @ingroup views_filter_handlers
*
* @ViewsFilter("boolean")
*/
class BooleanOperator extends FilterPluginBase {
...
ViewsFilter usually represents the class name for the annotation. From here, we can search for the plugin manager (core/modules/views/src/Plugin/ViewsHandlerManager.php).
Next, we need to determine the service: ( in file [ModuleName].services.yml )
...
plugin.manager.views.filter:
class: Drupal\views\Plugin\ViewsHandlerManager
arguments: [filter, '@container.namespaces', '@views.views_data', '@cache.discovery', '@module_handler']
...
You can load your service:
***
/**
*
* @var \Drupal\views\Plugin\ViewsHandlerManager $ViewsHandlerManager
*/
$ViewsHandlerManager = \Drupal::service('plugin.manager.views.filter');
$options = [];
/**
*
* @var \Drupal\views\Plugin\views\filter\BooleanOperator $instance
*/
$instance = $ViewsHandlerManager->createInstance('boolean', $options);