4

I want to know what difference does it make when i call a service this way :

$service = \Drupal::service('myservice.method');
$service->methodNameInService();

or this way (Dependency Injecton)

 public function __construct(MyService $myService) {
+    $this->myService = $myService;
   }

public function test() {
    // Call function from service 
    $this->myService->methodNameInService();

}

Is this better for performance or is it just only the right way and has it zero effect on performance or something else?

2
  • 2
    From the class level you should use dependency injection and not the static service container. From procedural code, the static service is the only option you have.
    – Kevin
    Jul 18 '18 at 14:03
  • 2
    Also, strive to type hint interfaces instead of concrete classes when possible.
    – Kevin
    Jul 18 '18 at 14:18
4

Dependency Injection has several advantages when you try to create test for your code, and follow the Single Responsibility Principle.

Really, the second reason is a consequence than the first: "The code is testeable because follow the SRP"

Furthermore, IDEs can recognize better the class type (and create autocompletes, f.e.) if the class is defined using DI. In a normal IDE, $service defined in $service = \Drupal::service('myservice.method'); has a unknown class.

In some places you cannot use DI (fe. in a .module) and you need to use the static load.

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.