Snippet: Simple PDO Wrapper

January 10, 2010 | Download
Tags: pdo, snippet, php

This simple wrapper stores a single instance of a PDO connection statically, so it can be recalled anywhere in an application without passing around a special variable. To use it, just call the getInstance method whenever a database connection is required.

/**
 * Simple PDO Wrapper
 * January 10, 2010
 * Corey Hart @ http://www.codenothing.com
 *
 *
 * The DB class provides a method to retrieve a singleton instance
 * of a database connection statically.
 *
 * Usage -
 * 	$conn = DB::getInstance();
 */ 

Class DB
{
	// Database Credentials
	const host = 'localhost';
	const user = 'someuser';
	const pass = 'somepass';
	const db = 'dbname';

	// Singleton Instance Storage
	private static $connection;

	// Returns singleton instance of a database connection
	public static function getInstance(){
		// Create a connection if not already done so
		if (!self::$connection){
			$config = "mysql:host=" . self::host . ";dbname=" . self::db;
			self::$connection = new PDO($config, self::user, self::pass);
		}

		// Return the connection instance
		return self::$connection;
	}
};

Download

Latest: php-simple-pdo-wrapper.zip
Released: January 10, 2010
-Initial Release
Have a question or comment? ask@codenothing.com.