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
External resources
-
Injecting services in your D8 plugins (lullabot.com)
- Great example and explanation of injecting services using the constructor/create pattern.
-
Services and dependency injection in Drupal 8 (drupal.org)
- Provides an overview of how a developer can utilize services and Dependency Injection in a module.
-
Services and Dependency Injection Container (api.drupal.org)
- Provides an overview of the Dependency Injection Container and Services in Drupal.
-
Service Container (symfony.com)
- Drupal uses a slightly modified version of the Symfony Service Container, and the Symfony documentation does a great job of explaining the problem the services and service containers are solving.