Recipe 10.15. Accessing a Database Connection Anywhere in Your Program
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.
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
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
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
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.