This document discusses services, dependency injection, and containers in Drupal 8. It defines a service as any PHP object that performs a global task. Services are defined in *.services.yml files and can be obtained either through service location from outside classes or through dependency injection inside classes. Dependency injection involves passing services as references into dependent objects to decouple classes and allow for loose coupling and testability. Services can also be overridden by defining new classes that implement the necessary interfaces and registering them as replacements.
3. What is a Service?
A Service is any PHP object that performs some sort of "global" task.
It's a purposefully-generic name used in computer science to describe an
object that's created for a specific purpose (e.g. delivering emails).
As a rule, a PHP object is a service if it is used globally in your application.
6. Obtaining Services: Service Location
// Get service from outside of a class.
$service = Drupal::service('service_name');
// If you have $container variable
$service = $container->get('service_name');
// Example services
$cache = Drupal::cache();
$lock = Drupal::lock()->acquire($lock_name)
8. Dependency Injection - Definition
Dependency injection is a software design pattern in which
one or more dependencies/services are injected, or passed by
reference , into a dependent object/client and are made part
of the client's state.
The pattern separates the creation of a client's dependencies
from its own behavior, which allows program designs to be
loosely coupled and to follow the dependency inversion and
single responsibility principles.
9. Obtaining Services: Dependency Injection
1. DI is used in classes.
2. If your class is a service, inject dependencies via arguments in *.services.yml
services:
path.alias_manager:
class: DrupalCorePathAliasManager // ¡®/core/lib/drupal/core/path/AliasManager.php¡¯
arguments: ['@path.alias_storage', '@path.alias_whitelist', '@language_manager', '@cache.data']
// code
public function __construct (AliasStorageInterface $storage,
AliasWhitelistInterface $whitelist,
LanguageManagerInterface $language_manager,
CacheBackendInterface $cache) {
10. Overriding Services
1. Locate default class and interface
2. Define a class that provides same services with different way implementing interface
and/or overriding the class, say
Drupalfoo_barMyNewServiceClass
1. Define a class that implements DrupalCoreDependencyInjectionServiceModifierInterface called
Drupalfoo_barFooBarServiceProvider
2. Put this in alter() method
public function alter(ContainerBuilder $container) {
$definition = $container->getDefinition('service.name');
$definition->setClass(Drupalfoo_barMyNewServiceClass);
}