Services and Dependency Injection in Drupal

Services are reusable PHP objects that encapsulate specific functionality or logic, as a module developer you’ll need to know how to discover and use existing services as well as author new ones for your application specific logic.

This course covers the fundamental concepts of services and the service container, including how to discover and use existing services, and the best practices for injecting these services into your code.

Key topics

  • What are services, their purpose, and how they work
  • What is dependency injection
  • Discovering and using existing services
  • Defining new services
  • Best practices for organizing and documenting service definitions

Note: This course is currently under development. For a hands-on introduction to services and dependency injection Drupal, refer to this chapter of our Module Developer Guide:

Tutorials in this course
Categories
Drupal 8, 9, 10, and 11
More information

It's best practice to access any of the services provided by Drupal via the service container to ensure the decoupled nature of these systems is respected. In order to do so, you need to know what services exists, and then, where possible, use dependency injection to use them in your code.

This tutorial walks through the process of:

  • Discovering existing services and learn their machine name
  • Using the machine name of service to request a copy from the service container
This course appears in the following guides:
Module Development
Learn how to alter Drupal with hooks, plugins, services, and events APIs.

Alter Drupal in Modules