Sometimes I encounter a public static function create() in plugin classes, for the example in the code show in Tutorial on Using Drupal 8 Plugin Derivatives Effectively.

public static function create(ContainerInterface $container, $base_plugin_id) {
  return new static(

Could you clarify me what the purpose of that function is, for example what it should do and where it's used?


create() is a factory method for dependency injection.

Plugins which implement ContainerFactoryPluginInterface are instantiated by create() of the plugin class:


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.