Created
January 15, 2010 19:42
-
-
Save shuber/278348 to your computer and use it in GitHub Desktop.
a simple php database connection manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class ConnectionManager { | |
static $configurations = array(); | |
static $connections = array(); | |
static function &connection($name) { | |
if (!isset(self::$connections[$name])) self::establish_connection($name); | |
return self::$connections[$name]; | |
} | |
protected static function establish_connection($name) { | |
if (isset(self::$configurations[$name])) { | |
$configuration = self::$configurations[$name]; | |
if (!isset($configuration['dbname'])) $configuration['dbname'] = array_delete('database', $configuration); | |
$adapter = array_delete('adapter', $configuration); | |
$username = array_delete('username', $configuration); | |
$password = array_delete('password', $configuration); | |
$connection_string = $adapter.':'; | |
$connection_string .= ($adapter == 'sqlite') ? $configuration['dbname'] : array_join_assoc('=', ';', $configuration); | |
self::$connections[$name] = new PDO($connection_string, $username, $password); | |
} else { | |
throw new InvalidArgumentException('Database configuration "'.$name.'" does not exist'); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function array_delete($key, &$array) { | |
$value = null; | |
if (isset($array[$key])) { | |
$value = $array[$key]; | |
unset($array[$key]); | |
} | |
return $value; | |
} | |
function array_join_assoc($assoc_glue, $glue, $array) { | |
$assoc_joins = array(); | |
foreach ($array as $key => $value) { | |
$assoc_joins[] = $key.$assoc_glue.$value; | |
} | |
return implode($glue, $assoc_joins); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment