OO Best Practice: Centralize the Connection

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
    Ready for the next problem? Our PDO object is configurable,
  • 0:09
    but we're still creating it inside of ShipLoader. What's going to happen if we add a battle table
  • 0:15
    and a battle loader? Will it also need to create its own PDO object?
  • 0:20
    Right now, yeah. So if we have 50 tables, that means 50 separate connections—the horror.
  • 0:29
    I want one connection that every class uses. Here's the goal. Move the new PDO call out of ShipLoader
  • 0:38
    so that it can be created in a central location and used by everyone. How?
  • 0:44
    By using the same strategy we just learned with configuration.
  • 0:48
    If you want to move something out of a service class, add it as a construct argument and pass it in.
  • 0:54
    Let's do it. Instead of passing in the three database options, we need to pass in the whole PDO object.
  • 1:03
    Replace the three arguments with just one, $pdo. Give it a type hint to be a great programmer.
Loading ...

OO Best Practice: Centralize the Connection

Loading...

Related to the previous tutorial where we implemented best practices to centralize our configuration, we also want to minimize the number of database connections. We want one connection that every class uses. In this tutorial we'll move the new PDO() call out of ShipLoader so that it can be created in a central location and used by everyone. How? By using the same strategy we just learned with configuration. If you want to move something out of a service class, add it as a __construct() argument and pass it in.

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

Additional resources:
There are no resources for this video. If you believe there should be, please contact us.