Module Development

OO Best Practice: Centralize Configuration for Drupal 8, 9

Sprout Video

Things are working pretty well, but we still have some things to clean up. In this tutorial we're going to review some best practices. Our current problem is that at the bottom of ShipLoader, our database connection information is hard-coded. That's a problem for two reasons. First, if this works on my computer, it probably won't work on production, unless everything matches up. Secondly, what if we need a database connection inside some other class? Right now, we'd just have to copy and paste those credentials into yet another spot, which is definitely not ideal.

Here's the goal: move the database configuration out of this class to somewhere more central so it can be re-used. The way you do this is fundamentally important to using object-oriented code correctly. The concept we are going to implement here is called dependency injection. The idea here is don't put configuration inside of a service class. Replace that hard-coded configuration with an argument. This allows anyone using your class to pass in whatever they want. The hard-coding is gone, and your class is more flexible.

Additional resources

Dependency Injection and the Art of Services and Containers series