5

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?

Thanks.

BigDiggers
  • 105
  • 1
  • 3
  • 8
  • Often, that's what I do. While it isn't the correct way of doing things, as far as OOP goes, it is easy. Of course you need to to be very careful about mixing your code with other libraries that might use the same variable names. See glasz answer for the proper way to go about doing this. – Brad Nov 07 '12 at 04:06

2 Answers2

6

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.

Community
  • 1
  • 1
glasz
  • 2,526
  • 25
  • 24
4

Look this project: Slim-PDO (github)

Documentation is here

Install via composer: $ composer require slim/pdo

Simple usage:

$app->container->singleton('database', function () use ($app) {
  return new \Slim\PDO\Database($app->config('db.dsn'), $app->config('db.usr'), $app->config('db.pwd'));
});

// SELECT * FROM users WHERE id = ?
$selectStatement = $app->database->select()
                       ->from('users')
                       ->where('id', '=', 1234);

$stmt = $selectStatement->execute();
$data = $stmt->fetch();

// INSERT INTO users ( id , usr , pwd ) VALUES ( ? , ? , ? )
$insertStatement = $app->database->insert(array('id', 'usr', 'pwd'))
                       ->into('users')
                       ->values(array(1234, 'your_username', 'your_password'));

$insertId = $insertStatement->execute(false);
Paramtamtаm
  • 312
  • 5
  • 12