0

Now I am creating a dbo object in each function on my php page. can a

define($dbh3, new PDO(...));//test

statement work? can I call a PDO object as a global constant? How can I create a common pdo connection? Do I have to create a pdo object in each function?

Current Situation:

$dbh = new PDO(...);
define($dbh3, new PDO(...));//test

function actorexists($name) {
  $dbh = new PDO(...);
  $s = $dbh->prepare("...");
}

function login($name, $password) {
  $dbh = new PDO(...);
  $s = $dbh->prepare("..."}
}

function actorbyname($name) {
  $dbh = new PDO(...);
  $s = $dbh->prepare("...;
}
Uğur Gümüşhan
  • 2,455
  • 4
  • 34
  • 62
  • I posted a singleton/factory pattern implementation as a solution for another post, a good place to start for sharing db connections across your code base. http://stackoverflow.com/questions/8440803/too-much-singletones-in-the-project-bad-practice/8441053#8441053 – Mike Purcell Dec 10 '11 at 00:03

2 Answers2

1

Definitely do not open a new connection for each SQL statement. This is very wasteful because you could run many queries during a single PHP request, and there is some overhead to opening a new socket and authenticating a MySQL user. It's not as bad as the overhead for Oracle or other databases, but it's something you should try to minimize where possible.

But you can't define a constant for your dbh.

http://php.net/define says:

...only scalar and null values are allowed. Scalar values are integer, float, string or boolean values.

In other words, an object instance or an array is not a legal value for a constant:

<?php

define('DB', new stdClass());


Warning: Constants may only evaluate to scalar values 
in test_define_constant_object.php on line 3

You can make your $dbh a global, but many PHP developers discourage using globals.

You can also use the Registry Pattern, which is basically a global array class that you can use in lieu of individual global variables. Do this in the bootstrap code for your script, so it gets run only once per request:

Zend_Registry::set("dbh", new PDO(...));

Then in your functions:

$dbh = Zend_Registry::get("dbh");
$s = $dbh->prepare("...");    
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
0

I would not define the object as a constant. Given your example, you can inject it where you need it.

function actorexists($pdo, $name) {
  $s = $pdo->prepare("...");
}

function login($pdo, $name, $password) {
  $s = $pdo->prepare("...");
}

function actorbyname($pdo, $name) {
  $s = $pdo->prepare("...");
}

$dbh = new PDO("...");
$exists = actorexists($dbh, 'foo');
$foo = actorbyname($dbh, 'foo');
Rob Apodaca
  • 834
  • 4
  • 8