Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

If you have a list of plugins of the same type, without knowing if you will need them, you can use a PluginBag to lazily instantiate them.

Therefore you need to replace the normal array ($this->examplePlugins in that example) in your code with an instance of a class which extends PluginBag.

// The constructor is just a suggestion.
  public function __construct(PluginManagerInterface $plugin_manager) {
    $this->examplePlugins = new ExampleBag($plugin_manager);
  }

Then your bag has to implement at least the initializePlugin($instance_id) method, which uses the manager to create an instance. This is some example code.

use Drupal\Component\Plugin\PluginBag;

class ExampleBag extends PluginBag {

  /**
   * Stores the plugin manager required to create an instance of a plugin.
   *
   * @var \Drupal\Component\Plugin::PluginManagerInterface
   */
  protected pluginManager;
 
  public function __construct($plugin_manager) {
    $this->pluginManager = $plugin_manager;
  }

  /**
   * Implements \Drupal\Component\Plugin\PluginBag::initializePlugin().
   */
  public function initializePlugin($instance_id) {
    $this->pluginInstances[$instance_id] = $this->pluginManager->createInstance($instance_id);
  }
Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done