OO Best Practice: Centralize Configuration

Video loading...

Join Drupalize.Me to watch this video

Join today and gain instant access to our entire video library.

Log in Sign up
  • 0:04
    Okay, next problem. At the bottom of ShipLoader,
  • 0:09
    our database connection information is hardcoded. That's a problem for two reasons.
  • 0:15
    First, if this works on my computer, it probably won't work in production
  • 0:21
    unless everything matches up. And second, what if we need a database connection inside some other class?
  • 0:28
    Right now, we just have to copy and paste these credentials into yet another spot. Ew.
  • 0:34
    Here's the goal. Move the database
  • 0:38
    configuration out of this class to somewhere more central so it can be reused.
  • 0:44
    And good news, the way you do this is fundamentally important to using object-oriented code correctly.
  • 0:52
    But first, let me tell you what you shouldn't do.
  • 0:56
    You should not just move this configuration
Loading ...

OO Best Practice: Centralize Configuration

Loading...

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.

Downloads: 
Log in or sign up to download companion files.