4

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?

1 Answer 1

7

By the definition of that class, anything that is not an object with injected dependencies is legacy code. That's a rather bold statement. ;)

In hooks, it is usually fine to use static methods on the Drupal class. Making that a service like suggested there is only useful if it's non-trivial code that someone might want to implement differently or/and you want to write unit tests for it.

If you're writing a service, plugins, form classes or controller classes, you should inject the dependencies.

So it's not really a question about which methods you should be using or not; it depends on where you would call it.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.