In Drupal 8 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.
Example of core services:
Generate a new UUID with uuid
service
$uuid = \Drupal::service('uuid')->generate();
get current path with path.current
service
$current_path = \Drupal::service('path.current')->getPath();
get alias of a path with path.alias_manager
service
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
Switch user sessions using Account Switcher service
// Call the account switcher service
$accountSwitcher = \Drupal::service('account_switcher');
// Switch to the other user
$account = \Drupal\user\Entity\User::load(1);
$accountSwitcher->switchTo($account);
Drupal 8's core services are located on : /core/core.services.yml
Example core services:
...
authentication:
class: Drupal\Core\Authentication\AuthenticationManager
arguments: ['@authentication_collector']
authentication_collector:
class: Drupal\Core\Authentication\AuthenticationCollector
tags:
- { name: service_collector, tag: authentication_provider, call: addProvider }
authentication_subscriber:
class: Drupal\Core\EventSubscriber\AuthenticationSubscriber
arguments: ['@authentication', '@current_user']
tags:
- { name: event_subscriber }
account_switcher:
class: Drupal\Core\Session\AccountSwitcher
arguments: ['@current_user', '@session_handler.write_safe']
user_permissions_hash_generator:
class: Drupal\Core\Session\PermissionsHashGenerator
arguments: ['@private_key', '@cache.bootstrap', '@cache.static']
current_user:
class: Drupal\Core\Session\AccountProxy
arguments: ['@event_dispatcher']
session_configuration:
class: Drupal\Core\Session\SessionConfiguration
arguments: ['%session.storage.options%']
...
To get All available services list
$services = \Drupal::getContainer()->getServiceIds();