Joachim Noreiko Suggests a Better Dependency Injection Management Route

codes
jamesmarkosborne / Pixabay

A recent blog post by Joachim Noreiko shares his discovery of a novel approach to dealing with dependency injection. The author begins by citing his regular approach while writing a class with dependency injection. However, this experience only resulted in repeatedly missing the services that needed to be added. Even in that case, the Module Builder’s capability of saving the configuration helped him edit and add more services.

According to the blog, the author realized that there was a different approach to this problem when a question was asked at Drupal Drinks. In this way, updating your code would be reduced to a simple find-and-replace.

Whenever you need a service, Joachim suggests writing  the code :

$service_entityTypeManager = \Drupal::service('entity_type.manager');

$stuff = $service_entityTypeManager->doSomething();

Then, only two find and replace operations are the only things needed to convert it to DI. The article also suggests using a regular expression like '(?<=::service..)[\w.]+' To find all the services needed for the class's dependency injection.

Reference: Changing your mind about dependency injection (24 October 2024)

Disclaimer: The opinions expressed in this story do not necessarily represent that of TheDropTimes. We regularly share third-party blog posts that feature Drupal in good faith. TDT recommends Reader's discretion while consuming such content, as the veracity/authenticity of the story depends on the blogger and their motives. 

Note: The vision of this web portal is to help promote news and stories around the Drupal community and promote and celebrate the people and organizations in the community. We strive to create and distribute our content based on these content policy. If you see any omission/variation on this please reach out to us at #thedroptimes channel on Drupal Slack and we will try to address the issue as best we can.

Related People

Upcoming Events