This requires three steps:
- Declare a property to hold the service.
- Implement a __construct() method to populate the property from step 1.
- Implement a create() method, to generate the service that is passed to __construct().
1) Declare a property to hold the service
In your class, declare the property that will hold the service.
/**
* The example service.
*
* @var \Drupal\example\Service\ExampleService
*/
protected $exampleService;
With this, you can now refer to $this->exampleService
within your class. However, at this point it is still NULL
, so it needs to be populated.
2) Implement a __construct() method to populate the property from step 1
This is done by overriding WidgetBase::__construct(), and adding the service to it.
public function __construct(
$plugin_id,
$plugin_definition,
FieldDefinitionInterface $field_definition,
array $settings,
array $third_party_settings,
ExampleServiceInterface $exampleService
) {
// Initialize the parent class:
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
$this->exampleService = $exampleService;
}
Now the property from step one can be populated when the class instantiated. However, the service itself needs to be generated, and passed to the __construct()
method.
3) Implement a create() method, to generate the service that is passed to __construct().
The service is generated in the create()
method. This is done by copying the code from WidgetBase::create(), and adding the service to it. WidgetBase::create() looks like this:
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['third_party_settings']
);
}
Notice that the values returned are the same values passed to the __construct()
method, but without the example.service
service. The example service needs to be retrieved from $container
and added to the above, by implemented create()
in your class as follows:
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['third_party_settings'],
$container->get('example.service')
);
}
This function call generates the example service, which passes it to __construct()
, which in turn populates $this->exampleService, so it can be used in your class in place of \Drupal::service('example.service')
.