Module Development

Use a Service in a Plugin for Drupal 8, 9, 10, and 11

Implementing plugins often involves accessing Drupal services to use their functions. Since plugins are PHP classes, we can use dependency injection to access services in our class. This tutorial demonstrates injecting dependencies into plugin classes. We'll update the HelloWorldBlock class to use the current_user service through dependency injection.

In this tutorial, we'll:

  • Learn how to inject dependencies into plugin classes.
  • Update the HelloWorldBlock class to use dependency injection for accessing the current_user service.

By the end of this tutorial, you should understand how to use dependency injection within plugin classes.

Drupal Module Developer Guide