Drupal Global Services, How to use global services in Drupal 8

By yuseferi, 25 August, 2016
Drupal Global Services, How to use global services in Drupal 8

One of the significant improvements of Drupal 8 that got me excited was the services & dependency-injection throughout the entire Drupal system. From aspects like routing, templating, managing configuration, querying and persisting data, you name it everything is done with services. it's fantastic because it grants developers a level of flexibility in extending Drupal that is far greater than what Drupal 7 was able to. by using well-disposed structure developers get ride of ravioli coding.

Hook architecture was good but in large projects with a lot of hook and modules put the developer in the hard situation, memory exhausting and performance issues were very common in large-scale Drupal 7 website.

I'll talk about how to create custom service later, here I just want to tell you Drupal 8's core provides several global services which you can easily access them.

How to access services in global functions

The global Drupal class provides static methods to access several of the most common services. As an example, Drupal::cache() returns the cache handler service or in another example Drupal::urlGenerator() returns the URL Generator service. If there is no dedicated method for the service you want to use, you can use the Drupal::service() method to retrieve any defined service.

Also, you can get the list of all available services with following Drush command

drush devel-container-services

 

or in  short way

 

drush dcs

 

List of Drupal 8.5 core services