Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the way to use PDO in slim framework?

Tags:

php

pdo

slim

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.

like image 985
BigDiggers Avatar asked Nov 07 '12 03:11

BigDiggers


2 Answers

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.

like image 183
glasz Avatar answered Sep 23 '22 16:09

glasz


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);
like image 28
Tarampampam Avatar answered Sep 24 '22 16:09

Tarampampam