Recipe 10.15. Accessing a Database Connection Anywhere in Your Program


Recipe 10.15. Accessing a Database Connection Anywhere in Your Program

10.15.1. Problem

You've got a program with lots of functions and classes in it, and you want to maintain a single database connection that's easily accessible from anywhere in the program.

10.15.2. Solution

Use a static class method that creates the connection if it doesn't exist and returns the connection (see Example 10-40).

Creating a database connection in a static class method

<?php class DBCxn {     // What DSN to connect to?     public static $dsn = 'sqlite:c:/data/zodiac.db';     public static $user = null;     public static $pass = null;     public static $driverOpts = null;     // Internal variable to hold the connection     private static $db;     // No cloning or instantiating allowed     final private function __construct() { }     final private function __clone() { }     public static function get() {         // Connect if not already connected         if (is_null(self::$db)) {             self::$db = new PDO(self::$dsn, self::$user, self::$pass,                                 self::$driverOpts);         }         // Return the connection         return self::$db;     } } ?>

10.15.3. Discussion

The DBCxn::get( ) method defined in Example 10-40 accomplishes two things: you can call it from anywhere in your program without worrying about variable scope and it prevents more than one connection from being created in a program.

To change what kind of connection DBCxn::get( ) provides, just alter the $dsn, $user, $pass, and $driverOpts properties of the class. If you need to manage multiple different database connections during the same script execution, change $dsn and $db to an array and have get( ) accept an argument identifying which connection to use. Example 10-41 shows a version of DBCxn that provides access to three different databases.

Handling connections to multiple databases

<?php class DBCxn {     // What DSNs to connect to?     public static $dsn =        array('zodiac' => 'sqlite:c:/data/zodiac.db',              'users' => array('mysql:host=db.example.com','monty','7f2iuh'),              'stats' => array('oci:statistics', 'statsuser','statspass'));     // Internal variable to hold the connection     private static $db = array();     // No cloning or instantiating allowed     final private function __construct() { }     final private function __clone() { }     public static function get($key) {         if (! isset(self::$dsn[$key])) {             throw new Exception("Unknown DSN: $key");         }         // Connect if not already connected         if (! isset(self::$db[$key])) {             if (is_array(self::$dsn[$key])) {                 // The next two lines only work with PHP 5.1.3 and above                 $c = new ReflectionClass('PDO');                 self::$db[$key] = $c->newInstanceArgs(self::$dsn[$key]);             } else {                 self::$db[$key] = new PDO(self::$dsn[$key]);             }         }         // Return the connection         return self::$db[$key];     } } ?>

In Example 10-41, you must pass a key to DBCxn::get( ) that identifies which entry in $dsn to use. The code inside get( ) is a little more complicated, too, because it has to handle variable numbers of arguments to the PDO constructor. Some databases, such as SQLite, just need one argument. Others may provide two, three, or four arguments. Example 10-41 uses the ReflectionClass::newInstanceArgs( ) method, added in PHP 5.1.3, to concisely call a constructor and provide arguments in an array. If you're using an earlier version of PHP, replace the calls to new ReflectionClass('PDO') and to newInstanceArgs( ) with the code in Example 10-42.

Calling the PDO constructor with older PHP versions

<?php $args = self::$dsn[$key]; $argCount = count($args); if ($argCount == 1) {     self::$db[$key] = new PDO($args[0]); } else if ($argCount == 2) {     self::$db[$key] = new PDO($args[0],$args[1]); } else if ($argCount == 3) {     self::$db[$key] = new PDO($args[0],$args[1],$args[2]); } else if ($argCount == 4) {     self::$db[$key] = new PDO($args[0],$args[1],$args[2],$args[3]); } ?>

Example 10-42 checks for each possible count of arguments to provide to the PDO constructor and invokes the constructor accordingly.

10.15.4. See Also

Documentation on PDO::__construct( ) at http://www.php.net/PDO::__construct and on ReflectionClass::newInstanceArgs( ) can be found at http://www.php.net/language.oop5.reflection.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net