Module Development
Topic

Services for Drupal 8, 9, and 10

As a development framework, Drupal core comes with a lot of useful objects for doing things like accessing the database, sending email, or making HTTP requests. Generally speaking almost everything that Drupal does is actually done by one of these objects. In Drupal, these objects are called services and in order to make working with them easier they are generally accessed via the service container.

To keep things flexible and not tied to any one specific way of doing things these service objects implement a known interface and can be exchanged for other services that implement the same interface without affecting the code using the service. This allows Drupal to do things like work with multiple different database servers, or for a module to override Drupal’s mail handling and send all emails through a third party service instead.

As a developer you’ll use the service container to access existing services in order to use the functionality they provide. You’ll define new services in order to encapsulate your unique application logic in a reusable way. Some Drupal subsystems require you to define services and register a service class in order to use them.

Example tasks

  • Request a service from the service container so you can use it in your code. For example, send an email.
  • Define a new service
  • Subscribe to an event
  • Override an existing service

Confidence

Drupal builds on the Symfony service container, which has been quite stable. The way that you define, and use, services has changed very little since they were introduced in Drupal. We don’t anticipate any major changes. This means that older documentation resources are likely still useful long after their publication date.

Drupalize.Me resources

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
Categories
Drupal 8, 9, and 10
More information

Dependency injection is a design pattern commonly used in object-oriented software architectures in order to support Inversion of Control.

Drupal 8, 9, 10, and 11
More information

Object-oriented PHP utilizes classes and objects to organize code into reusable chunks. This approach helps us organize complex applications, such as Drupal, into modular code called classes that can be reused across the entire system.

Guides

Not sure where to start? Our guides provide useful learning tracks for all skill levels.

Navigate guides

External resources