InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Accessing a Database Connection Anywhere in Your Program in PHP
PHP

Accessing a Database Connection Anywhere in Your Program in PHP

InfinityCoder December 6, 2016

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).
Example 10-40. Creating a database connection in a static class method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
   }
}

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, 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.
Example 10-41. Handling connections to multiple databases

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class DBCxn {
   // What DSNs to connect to?
   public static $dsn =
      rray('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])) {
 
              $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 to concisely call a constructor and provide arguments in an array.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Accessing an Object Using Array Syntax in PHP
You have an object, but you want to be able …

Accessing an Object Using Array Syntax in PHP

Modifying Data in an SQL Database in PHP
You want to add, remove, or change data in an …

Modifying Data in an SQL Database in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap