Matt Glaman on Dependency Injection Anti-Patterns

When auditing a Drupal codebase, one of the first areas to review is dependency injection anti-patterns found in custom code and contributed modules. The recent blog post by Matt Galaman emphasizes that accessing services statically through \Drupal is not the anti-pattern but rather resides within the __construct method of a class.

It is generally recommended to keep constructors simple when using dependency injection. The purpose of the __construct method is to assign dependencies as properties, and adding extra logic to constructors can lead to unexpected behavior, violating the single responsibility principle. The article points out common examples of this anti-pattern, such as assigning the current request object, entity storage, or configuration objects directly to properties instead of retrieving them when needed.

The anti-pattern causes additional code execution in the constructor and can result in invalid objects if system changes occur between service construction and code execution. It is advised to retrieve data from stack or factory services only at the time of need.

While these practices may seem like micro-optimizations, the article emphasizes that such anti-patterns have caused quirky bugs in the past. Additionally, if performance is a concern, optimizing for every millisecond counts.

In summary, the article highlights the importance of avoiding dependency injection anti-patterns in the __construct method and suggests retrieving necessary data at the time of need instead of assigning them as properties. Click here to read the blog post.

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 let us know in the comments below and we will try to address the issue as best we can.

Advertisement Here

Upcoming Events

Latest Opportunities

Advertisement Here