When reading the documentation for the Drupal class, I notice the following sentence:
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.
The example code that uses a service in a hook implementation, is the following one.
// The preferred way: dependency injected code.
function hook_do_stuff() {
// 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();
}
interface StuffDoingInterface {
public function doStuff();
}
class StuffDoingClass implements StuffDoingInterface {
protected $lockBackend;
public function __construct(LockBackendInterface $lockBackend) {
$this->lockBackend = $lockBackend;
}
public function doStuff() {
$lock = $this->lockBackend->acquire('stuff_lock');
// ...
}
}
The code is still using the Drupal
class.
Should my code use the Drupal class? Are there any methods of that class I should avoid using in Drupal 8 code written from scratch?