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

Plugins that require injected dependencies can implement \Drupal\Core\Plugin\ContainerFactoryPluginInterface.

This interface contains a single public static function named create():

<?php
 
/**
   * Creates an instance of the plugin.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *    The DI Container
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   *
   * @return static
   *   Returns an instance of this plugin.
   */
 
public static function create(ContainerInterface $container, array $configuration, $plugin_id, array $plugin_definition) {
  }
?>

A fictional example implementation where the plugin constructor requires the plugin.manager.entity service.

<?php
/**
 * @file
 * Contains \Drupal\foo\Plugin\Bar\FooBar.
 */
namespace Drupal\foo\Plugin\Bar;

use
Drupal\Core\Bar\FooBarBase;
use
Drupal\Core\Entity\EntityManagerInterface;
use
Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use
Symfony\Component\DependencyInjection\ContainerInterface;

class
FooBar extends FooBarBase implements ContainerFactoryPluginInterface {

 
/**
   * The entity manager service
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
 
protected $entityManager;

 
/**
   * Constructs a Drupal\Component\Plugin\PluginBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   */
 
public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityManagerInterface $entity_manager) {
   
parent::__construct($configuration, $plugin_id, $plugin_definition);
   
$this->entityManager = $entity_manager;
  }

 
/**
   * {@inheritdoc}
   */
 
public static function create(ContainerInterface $container, array $configuration, $plugin_id, array $plugin_definition) {
    return new static(
     
$configuration,
     
$plugin_id,
     
$plugin_definition,
     
$container->get('plugin.manager.entity')
    );
  }

}
?>
Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done