From Services and dependency injection in Drupal 8
In Drupal 8 speak, a service is any object managed by the services container.
Drupal 8 introduces the concept of services to decouple reusable functionality and makes these services pluggable and replaceable by registering them with a service container. As a developer, it is 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. The Symfony 2 documentation has a great introduction to services.
As a developer, services are used to perform operations like accessing the database or sending an e-mail. Rather than use PHP's native MySQL functions, we use the core-provided service via the service container to perform this operation so that our code can simply access the database without having to worry about whether the database is MySQL or SQLlite, or if the mechanism for sending e-mail is SMTP or something else.
Services can depend on other services. For example, path.alias_manager
depends
on path.alias_storage
, path.alias_whitelist
, path.language_manager
and cache.manager
:
path.alias_manager:
class: Drupal\Core\Path\AliasManager
arguments: ['@path.alias_storage', '@path.alias_whitelist', '@language_manager', '@cache.manager']
This ensures these services are passed into the path.alias_manager
constructor:
<?php
class AliasManager implements AliasManagerInterface, CacheDecoratorInterface {
// ...
/**
* Constructs an AliasManager.
*
* @param \Drupal\Core\Path\AliasStorageInterface $storage
* The alias storage service.
* @param \Drupal\Core\Path\AliasWhitelistInterface $whitelist
* The whitelist implementation to use.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
* Cache backend.
*/
public function __construct(AliasStorageInterface $storage, AliasWhitelistInterface $whitelist, LanguageManagerInterface $language_manager, CacheBackendInterface $cache) {
$this->storage = $storage;
$this->languageManager = $language_manager;
$this->whitelist = $whitelist;
$this->cache = $cache;
}
// ...
}
?>