I use a static function to create a PDO object.
It accepts 2 params:
a string and an object which contains the connection settings (dns, user, pass).
in order to prevent unnecessarily creating duplicate PDO connections with the same name, I tried to create a multi-key dictionary to cache the PDO object in.
Here is what I did:
include_once('IPDOSettings.php');
class PDOManager
{
private static $connections; // array of connections
public static function getConnection(IPDOSettings $settings, $connection_name = 'default')
{
$dictionary_key = array('name' => $connection_name, 'settings' => $settings);
if(!self::$connections[$dictionary_key])
{
$DBH = new PDO($settings->getDNS(),$settings->getUser(),$settings->getPass());
self::$connections[$dictionary_key] = $DBH;
}
return self::$connections[$dictionary_key];
}
}
However after testing this I get this error Illegal offset type. After looking it up I find out that you cannot use objects or arrays as keys.
So is there anyway to do what I am trying to achieve?
Not really an answer to your question but do you expect
PDOManager::getConnection()being called multiple times with the same$connection_namebut different settings? Do you need to store the settings along with the db handle in your cache?This problem wouldn´t even occur if you´d just store the connections by name:
EDIT:
Well, if you cant just use
$connection_nameas a key, you could combine$connection_nameand usespl_object_hash()in order to get your key:This is much nicer then e. g. using
serialize()to get a string representation of the$settingsobject.