Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By dawehner on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Issue links:
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