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

The PluginBag is an abstract base class to help provide a way to both lazy-load plugins, and encapsulate their instantiation logic.

There are two types of plugin bags, ones that will only ever contain one plugin instance, and those that will contain 0-N plugin instances.

If the object using the plugin bag (usually a ConfigEntity) will only ever contain a single plugin instance, then it can use the \Drupal\Component\Plugin\DefaultSinglePluginBag:

$plugin_bag = new DefaultSinglePluginBag($plugin_manager, array($plugin_id), $configuration);

If the object will be using many different plugin instances, the \Drupal\Component\Plugin\DefaultPluginBag class can be used:

$plugin_bag = new DefaultPluginBag($plugin_manager, $configuration);

In this case, the configuration for each instance should contain a key/value pair of id: the_plugin_id.
If your configuration uses a different key than 'id', you need to subclass DefaultPluginBag.
It is also customary to always subclass and override the get() method for typehinting purposes.

namespace Drupal\mymodule;

use Drupal\Component\Plugin\DefaultPluginBag;

class MyModulePluginBag extends DefaultPluginBag {

  /**
   * {@inheritdoc}
   */
  protected $pluginKey = 'mypluginkey';

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\mymodule\MyModulePluginInterface
   */
  public function &get($instance_id) {
    return parent::get($instance_id);
  }
}
Impacts: 
Module developers