Haulyn Jason Haulyn Jason - 1 year ago 94
PHP Question

what is the way to use PDO in slim framework?

I start a new slim project with twig support, I want to use PDO as database layer, what is the way to integrate? or just use GLOBAL $db?


Answer Source

i'm against mutable globals. you could use a simple factory method returning your connection:

function db() {
  static $db = null;
  if (null === $db)
    $db = new PDO(...);
  return $db;

if you're about to deal with more of such problems, consider a registry (see this one).

Regarding mutable globals:

I'm against such things because, well, they are easy to be mutated.
What happens if, during the flow of a program, circumstances change unexpectedly?
Things break.

If you're the only one working on the project, globals might be ok.
But from my experience, even in this scenario, keeping track of global variables becomes a hassle and offends logical organisation of your code.
What if you come to the point of sharing your code with other who will overwrite such global?

Also, globals contradict the methodology of data encapsulation in the context of seperation of concerns.

All this plays into the big, wide science of software architecture.

Additionally, using a factory in this specific case ensures that you only keep one single reference to the connection to your database.