7

Sometimes I encounter a function public static function create with arguments in plugin classes.

For example, here https://www.sitepoint.com/tutorial-on-using-drupal-8-plugin-derivatives-effectively/ we can see it.

public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity.manager')->getStorage('node')
    );
  }

Could you clarify me, what is the function for? What should it do and where is it used?

7

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);
}
5

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.