Drupal - What is public static function create() in plugins for?
create() is a factory method for dependency injection.
Plugins which implement ContainerFactoryPluginInterface
are instantiated by create()
of the plugin class:
ContainerFactory::createInstance
public function createInstance($plugin_id, array $configuration = []) {
...
// If the plugin provides a factory method, pass the container to it.
if (is_subclass_of($plugin_class, 'Drupal\Core\Plugin\ContainerFactoryPluginInterface')) {
return $plugin_class::create(\Drupal::getContainer(), $configuration, $plugin_id, $plugin_definition);
}
// Otherwise, create the plugin directly.
return new $plugin_class($configuration, $plugin_id, $plugin_definition);
}
It's the static method Drupal core uses to create the plugin. (See, for example, the documentation for SystemMenuBlock::create()
.)
Drupal core doesn't instantiate a plugin with new PluginClass()
, but PluginClass::create()
. This allows the class implementing the plugin to return an instance previously created.
The other pro is that the signature of the plugin constructors can vary without giving problems to Drupal, which just requires the create()
method of a class of plugins to always have the same signature.
It is the same pattern used for Drupal services.