Drupal helper class for procedural code that needs services

Generally, code in Drupal should accept its dependencies via either constructor injection or setter method injection. However, there are cases, particularly in legacy procedural code, where that is infeasible. The Drupal class acts as a unified global accessor to arbitrary services within the system in order to ease the transition from procedural code to injected OO code.

The container is built by the kernel and passed in to this class which stores it statically. The container always contains the services from core/core.services.yml, the service YAML files of enabled modules and any other YAML files defined in $GLOBALS['conf']['container_yamls'].

This class exists only to support legacy code that cannot be dependency injected. If your code needs it, consider refactoring it to be object oriented, if possible. When this is not possible, for instance in the case of hook implementations, and your code is more than a few non-reusable lines, it is recommended to instantiate an object implementing the actual logic.

<?phpfunction hook_do_stuff() {// Move the actual implementation to a class and instantiate it.$instance = new StuffDoingClass(Drupal::lock());$instance->doStuff();

// Or, even better, rely on the service container to avoid hard coding a // specific interface implementation, so that the actual logic can be // swapped. This might not always make sense, but in general it is a good // practice.Drupal::service('stuff.doing')->doStuff();}