How to properly set up a PDO connection

后端 未结 4 1541
温柔的废话
温柔的废话 2020-11-21 07:24

From time to time I see questions regarding connecting to database.
Most answers is not the way I do it, or I might just not get the answers correctly. Anyway; I\'ve nev

4条回答
  •  有刺的猬
    2020-11-21 08:10

    I would suggest not using $_SESSION to access your DB connection globally.

    You can do one of a few things (in order of worst to best practices):

    • Access $dbh using global $dbh inside of your functions and classes
    • Use a singleton registry, and access that globally, like so:

      $registry = MyRegistry::getInstance();
      $dbh = $registry->getDbh();
      
    • Inject the database handler into the classes that need it, like so:

      class MyClass {
          public function __construct($dbh) { /* ... */ }
      }
      

    I would highly recommend the last one. It is known as dependency injection (DI), inversion of control (IoC), or simply the Hollywood principle (Don't call us, we'll call you).

    However, it is a little more advanced and requires more "wiring" without a framework. So, if dependency injection is too complicated for you, use a singleton registry instead of a bunch of global variables.

提交回复
热议问题