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?

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.

  • If I understand correctly, in the case I really need to use a service for my code, then I should not call those Drupal methods that return services; in the other cases, I could call any methods of that class. Is that correct? – kiamlaluno Aug 28 '13 at 12:04
  • I'm not sure if I understand your question correctly :) Not only if you define a service yourself, but also a controller (there's now ControllerBase so $this->method() is almost a 1:1 replacement for \Drupal::method()), a form or implement a plugin like a block. – Berdir Aug 28 '13 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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